将列附加到列表中的每个数据框架
我有一个数据帧列表,并想为每个数据帧附加一个新列,但是我不断收到各种错误消息。谁能解释为什么下面的代码对我不起作用?如果 rowid_to)column 可以正常工作,我会很高兴,因为我的实际集中的数据可以正确排序,否则我想要一个新列,其中的列表来自 1:length(data$data)
##dataset
data<- tibble(Location = c(rep("London",6),rep("Glasgow",6),rep("Dublin",6)),
Day= rep(seq(1,6,1),3),
Average = runif(18,0,20),
Amplitude = runif(18,0,15))%>%
nest_by(Location)
###map + rowid_to_column
attempt1<- data%>%
map(.,rowid_to_column(.,var = "hour"))
##mutate
attempt2<-data %>%
map(., mutate("Hours" = 1:6))
###add column
attempt3<- data%>%
map(.$data,add_column(.data,hours = 1:6))
newcolumn<- 1:6
###lapply
attempt4<- lapply(data,cbind(data$data,newcolumn))
非常感谢, 斯图尔特
I have a list of dataframes and want to append a new column to each, however I keep getting various error messages. Can anybody explain why the below code doesn't work for me? I'd be happy if rowid_to)column works as the data in my actual set is alright ordered correctly, otherwise i'd like a new column with a list going from 1:length(data$data)
##dataset
data<- tibble(Location = c(rep("London",6),rep("Glasgow",6),rep("Dublin",6)),
Day= rep(seq(1,6,1),3),
Average = runif(18,0,20),
Amplitude = runif(18,0,15))%>%
nest_by(Location)
###map + rowid_to_column
attempt1<- data%>%
map(.,rowid_to_column(.,var = "hour"))
##mutate
attempt2<-data %>%
map(., mutate("Hours" = 1:6))
###add column
attempt3<- data%>%
map(.$data,add_column(.data,hours = 1:6))
newcolumn<- 1:6
###lapply
attempt4<- lapply(data,cbind(data$data,newcolumn))
Many thanks,
Stuart
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您几乎尝试了基本R的尝试,但是您想迭代
Data $ Data
,这是数据帧列表。编辑:随着实现的更新,它是在列而不是行上迭代的。如果数据帧具有不同数量的行,则该方法将起作用,该方法使用该方法定义为
1:6
不会。You were nearly there with your base R attempt, but you want to iterate over
data$data
, which is a list of data frames.Edit: Updated as realised it was iterating over columns rather than rows. This approach will work if the data frames have different numbers of rows, which the methods with the vector defined as
1:6
will not.data.table
方法a
data.table
approach一种
purrr
方法:如果你想使用你的方法并保留相同的数据结构,这是再次使用
purrr
的方法(你需要取消分组,否则它将不起作用由于按行分组)A
purrr
approach:If you want to use your approach and preserve the same data structure, this is a way again using
purrr
(you need to ungroup, otherwise it will not work due to the rowwise grouping)