简体   繁体   中英

R: filter() in for loop running through columns

in R - trying to loop through a list of column names, filtering by a specific entry and counting the number of occurrences of that entry. I'm trying to run something like what's below in a pipe within the for loop to do this - but I can't get what's below to work unless I substitute questionNumbers[i] for a direct column name.

df %>%
nrow(filter(questionNumbers[i] == Response[1])) %>%
....etc

Any ideas? I have a feeling there's an apply() way to do this - thoughts?

so assuming that you have a data.frame (I'll play with mtcars ) and a vector of results ( c(1,2) ) that you're looking for. The following mixture of lapply will work with the tibble , and tidyr packages.

responses = c(1,2)

#create a named list
exampleOutput <- lapply(setNames(names(mtcars),names(mtcars)), function(x){
  lapply(setNames(responses, paste0('response_', responses)),function(y){
    mtcars[mtcars[x] == y, x] %>%
      length
  }) %>% 
    #convert named list into a tibble/dataframe
    tibble::as.tibble()
}) %>%
  #convert list into a tibble/dataframe
  tibble::enframe() %>%
  #open up the nested data
  tidyr::unnest()

you'll get something like this

  name  response_1 response_2
   <chr>      <int>      <int>
 1 mpg            0          0
 2 cyl            0          0
 3 disp           0          0
 4 hp             0          0
 5 drat           0          0
 6 wt             0          0
 7 qsec           0          0
 8 vs            14          0
 9 am            13          0
10 gear           0          0
11 carb           7         10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM