簡體   English   中英

R:for循環中各列的filter()

[英]R: filter() in for loop running through columns

在R中-嘗試遍歷列名列表,按特定條目進行過濾並計算該條目的出現次數。 我正在嘗試在for循環中的管道中運行以下內容來執行此操作-但除非我用questionNumbers[i]代替直接列名,否則我無法獲得以下內容。

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

有任何想法嗎? 我覺得有一個apply()方法可以做到這一點-有想法嗎?

因此,假設您有一個data.frame (我將與mtcars一起mtcars )和要尋找的結果向量( c(1,2) )。 以下混合物lapply將與工作tibbletidyr包。

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()

你會得到這樣的東西

  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM