dplyr过滤器和R中的for循环

时间:2019-03-07 03:52:11

标签: r loops for-loop filter dplyr

所有数据结构都是数据帧。 我在R中使用dplyr语法编写。 我想将此代码替换为for循环。

rbind(
query0226 %>% 
  filter(t1.cate == tb0226_cate_below_100$Var1[1]) %>% select(t1.query, t1.cate),
query0226 %>% 
  filter(t1.cate == tb0226_cate_below_100$Var1[2]) %>% select(t1.query, t1.cate),
query0226 %>% 
  filter(t1.cate == tb0226_cate_below_100$Var1[3]) %>% select(t1.query, t1.cate),
query0226 %>% 
  filter(t1.cate == tb0226_cate_below_100$Var1[4]) %>% select(t1.query, t1.cate),
query0226 %>% 
  filter(t1.cate == tb0226_cate_below_100$Var1[5]) %>% select(t1.query, t1.cate),
query0226 %>% 
  filter(t1.cate == tb0226_cate_below_100$Var1[6]) %>% select(t1.query, t1.cate)
)

所以我写了下面的代码,但它不起作用。 哪一部分错了?

for (i in 1:length(tb0226_cate_below_100$Var1)){
  rbind(
    query0226 %>% 
      filter(t1.cate == tb0226_cate_below_100$Var1[i]) %>% select(t1.query, t1.cate)
  )
}

1 个答案:

答案 0 :(得分:0)

你可以做

temp <- data.frame()
for (i in unique(tb0226_cate_below_100$Var1)){
  temp = rbind(temp, query0226 %>% filter(t1.cate == i) %>% select(t1.query,t1.cate))
}

,现在temp是最终的数据帧。如果unique仅具有唯一记录,则可以删除Var1

已通过mtcars数据集进行了验证

rbind(
   mtcars %>% filter(cyl ==4) %>% select(mpg, disp), 
   mtcars %>% filter(cyl ==6) %>% select(mpg, disp), 
   mtcars %>% filter(cyl ==8) %>% select(mpg, disp)
)

temp <- data.frame()
for (i in unique(mtcars$cyl)){
   temp = rbind(temp,mtcars %>% filter(cyl==i) %>% select(mpg, disp))
}