简体   繁体   English

如何使用过滤器函数进行for循环?

[英]How do I make a for loop with the filter function?

I'm having a problem with using the filter() function inside a for loop , it doesn't filter the data frame and instead creates an i value. 我在for loop使用filter()函数时遇到问题,它不过滤数据帧,而是创建一个i值。 The code is below: 代码如下:

    library(tidyverse)
    library(magrittr)
    library(dplyr)
    funcexrds <- readRDS("C:/Users/chlav/Dropbox/Antidumping/Data/ano_pais_imp/funcex.rds")
    funcexrds <- funcexrds %>% arrange(desc_cnae, pais)
    View(funcexrds)
    funcexpais_lista <- funcexrds %>% select(pais) %>% as.list()
    funcexcnae_lista <- funcexrds %>% select(desc_cnae) %>% as.list()
    subset1 <- filter(funcexrds, pais == "África do Sul", desc_cnae == "Abate de reses, exceto suínos")
    for (i in 1:length(unique(funcexpais_lista))) {
        funcexrds_t <- filter(funcexrds, pais == "i") 
    }

As you can see if you reproduce the code, subset1 returns the filtered dataset as you expect, but the for loop doesn't 如您所见,如果您重新生成代码,则subset1返回已过滤的数据集,但是for循环不会

I agree with @Clemsang. 我同意@Clemsang。 If you're trying to get the for loop to pull out whatever relevant information is at Pais == 1, Pais == 2, etc. putting i outside of quotes effectively shows the for loop where to put the number you indicated in 如果您尝试获取for循环以提取Pais == 1或Pais == 2处的所有相关信息,等等。将i放在引号之外有效地显示了for循环将您指定的数字放在哪里

for (i in 1:length(unique(funcexpais_lista)))

Also just some housekeeping to keep in mind, since tidyverse already contains the dplyr and magrittr functions, you should only need to load tidyverse before starting your code! 还要记住一些内务处理,因为tidyverse已经包含dplyr和magrittr函数,因此您只需要在启动代码之前加载tidyverse!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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