【发布时间】:2020-07-08 19:44:53
【问题描述】:
我修改了虹膜数据以重新创建我的问题的简单版本:
library(purrr)
library(dplyr)
#Modify the dataset
data(iris)
iris$Sepal.Length.2019<-iris$Sepal.Length
iris$category<-ifelse(iris$Petal.Width<1.3,"small","big")
#Split the dataframe into multiple dataframes based on Species
list<-split(iris,iris$Species)
start_year<-c(2020)
End_year<-c(2022)
#Function (Failed)
manipulate<-map(x){
for(i in start_year:End_year){
#Step 1:Create a new column with year suffix
x[,paste("Sepal.Length",i,sep=".")]<-x[,paste("Sepal.Length",i-1,sep="."]*2
#step 2 (The problem step):sort each dataframe based on value for a given year and category variable to create a cumsum of the sorted value
x<- x %>% group_by(category) %>% arrange(x[,paste("Sepal.Length",i,sep=".")])
%>% mutate(x[,paste("Sum.Sepal.Length",i,sep=".")]=cumsum( x[,paste("Sepal.Length",i,sep=".")]))
#Step 3: perform more analysis with Sum.Sepal.Length
x[,paste("Sum.Length.Compare",i,sep=".")]<-ifelse(x[,paste("Sum.Sepal.Length",i,sep=".")]>2,"Good","Bad")
return(x)
}
}
#Map this over list
new_list<-map(list,manipulate)
由于第 2 步,我收到一个错误,可能是因为我混合了很多不同的元素。这里应该使用其他包或公式吗?循环的目标是以迭代方式基于现有列创建新列。
我对使用 purrr 和应用家庭真的很陌生。任何帮助将非常感激! 谢谢!
【问题讨论】:
-
嗨@ghq90。您能否请一些示例输入数据以及您期望的输出是什么?从代码中很难理解列的格式。
-
嗨@ArtemSokolov,感谢您的评论。我添加了一些例子。预期的输出应该在列表中的每个数据框中都有新列。