【发布时间】:2021-09-06 12:48:11
【问题描述】:
我在编写 for 循环方面是个菜鸟,可以使用一些支持让我的工作。我有一个数据框,我想根据存储在向量中的值进行过滤。我需要多次过滤数据框,对向量中的每个值一次。在每个过滤器之后,我想存储子集数据帧并将所有数据帧绑定在一起。
我发现了这个超级方便的代码,关于如何存储每个过滤数据集的结果并绑定在一起 - Append data frames together in a for loop
但是,我无法让代码循环遍历向量中的每个值。它只循环第一个值。
这是一个例子:
area <- data.frame(
land = c("68N03E220090", "68N03E244635", "68N03E244352", "68N03E223241"),
type = c("home", "mobile", "home", "vacant"),
object_id = c(NA, 7, NA, 34)
)
block <- c("68N03E22", "68N03E24")
datalist = list()
for (value in block){
df <- area %>% filter(is.na(object_id) & grepl(paste0("^", block),land))
df$value <- value
datalist[[value]] <- df # add it to your list
}
df_filtered <- dplyr::bind_rows(datalist)
我收到警告:
Warning messages:
1: In grepl(paste0("^", block), land) :
argument 'pattern' has length > 1 and only the first element will be used
2: In grepl(paste0("^", block), land) :
argument 'pattern' has length > 1 and only the first element will be used
【问题讨论】:
-
area %>% group_split(s = str_extract(land, str_c('^', block, collapse = '|')))
标签: r