我有一个复杂的函数,它通过使用数据帧中的id列来返回数据帧,我想将该函数应用于每个唯一的id。最后,我将为每个唯一的id创建一个数据帧,最后我想将它们组合成一个表。像这样的东西。
data <- data.frame(c = c("A", "A", "B", "B", "C", "C"),
num = (seq(1,6))) # this is the dataframe
test <- function(group, city){
df = data[data$c == group, ]
df$d <- city
return(data.frame(df))
} # function
# applying to each group
df <- test("A", "Chicago")
df1 <- test("B", "New York")
df2 <- test("C", "Los Angeles")
# combine all the dataframe
final <- rbind(df, df1, df2)
我如何在R中实现这一点,而不手动将函数应用于每组?希望使用dplyr和purr。谢谢
一种方法是使用map
(map2
,因为您有两个参数(生成数据帧列表,然后使用bind_rows
将列表中的元素组合为一个数据集(此处为文档(。
类似这样的东西:
arg1 = c("A","B","C")
arg2 = c("Chicago", "New York", "Los Angeles")
list_of_dataframes = map2(arg1, arg2, test)
single_dataframe = bind_rows(list_of_dataframes)
编辑:根据您的评论,也许您想要的是for循环?这可能更容易思考,但错过了R的一些优雅。
# create empty dataframe
output_df = data.frame(stringsAsFactors = FALSE)
for(i in 1:length(arg1)){
# make dataframe for i-th combination of inputs
this_df = test(arg1[i], arg2[i])
# append i-th df to output
output_df = bind_rows(output_df, this_df)
}
请注意,不需要对arg1
和arg2
进行迭代。您对函数的输入可以是任意的。