Home > database >  Loop in tidyverse
Loop in tidyverse

Time:01-29

I am learning tidyverse() and I am using a time-series dataset, and I selected columns that start with sec. What I would like basically to identify those values from columns that equal 123, keep these and have the rest replace with 0. But I don't know how to loop from sec1:sec4. Also how can I sum() per columns?

df1<-df %>% 
  select(starts_with("sec")) %>% 
  select(ifelse("sec1:sec4"==123, 1, 0))
  

Sample data:

structure(list(sec1 = c(1, 123, 1), sec2 = c(123, 1, 1), sec3 = c(123, 
0, 0), sec4 = c(1, 123, 1)), spec = structure(list(cols = list(
    sec1 = structure(list(), class = c("collector_double", "collector"
    )), sec2 = structure(list(), class = c("collector_double", 
    "collector")), sec3 = structure(list(), class = c("collector_double", 
    "collector")), sec4 = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), delim = ","), class = "col_spec"),  row.names = c(NA, 
-3L), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"))

CodePudding user response:

I think you would have to use mutate and across to accomplish this. below you will mutate across each column starting with sec and then keep all values that are 123 and replace all others with 0.

 df1<-df %>% 
        select(starts_with("sec")) %>% 
        mutate(across(starts_with("sec"),.fns = function(x){ifelse(x == 123,x,0)}))
  •  Tags:  
  • Related