【发布时间】:2014-09-10 07:11:31
【问题描述】:
我在网上搜索了帖子以找到解决方案。但是,我无法识别任何东西。因此,我决定请求您的帮助。我有一个包含数据框的列表。我从每个数据框中选择了某些列并将它们组合起来。当我合并来自两个数据框的数据时,我想添加一个包含列表名称的列。但是,我无法做到这一点。这是一个示例数据以及我尝试过的内容。
样本数据和我的尝试
### 1st dataframe
time <- seq(as.Date("2014-09-01"), by = "day", length.out = 12)
temperature <- sample(c(15:26), replace = TRUE)
weather <- sample(c("clear", "cloudy", "rain"), size = 12, replace = TRUE)
rome <- data.frame(time, temperature, weather, stringsAsFactors = F)
### 2nd dataframe
time <- seq(as.Date("2014-09-01"), by = "day", length.out = 12)
temperature <- sample(c(12:23), replace = TRUE)
weather <- sample(c("clear", "cloudy", "rain"), size = 12, replace = TRUE)
paris <- data.frame(time, temperature, weather, stringsAsFactors = F)
### Assign names to each data frame and create a list
ana <- list(rome = rome, paris = paris)
#Here are a bit of data.
#> ana
#$rome
# time temperature weather
#1 2014-09-01 19 cloudy
#2 2014-09-02 21 cloudy
#3 2014-09-03 17 clear
#$paris
# time temperature weather
#1 2014-09-01 18 clear
#2 2014-09-02 12 cloudy
#3 2014-09-03 17 cloudy
### Select 1st and 2nd column from each data frame in the list and
### combine them.
rbind.fill(lapply(ana, `[`, 1:2))
我想在此处添加一些内容,以使用新列位置创建以下理想结果。请注意,我修剪了理想的结果以节省空间。
time temperature location
1 2014-09-01 19 rome
2 2014-09-02 21 rome
3 2014-09-03 17 rome
13 2014-09-01 18 paris
14 2014-09-02 12 paris
15 2014-09-03 17 paris
我尝试过的一件事是按以下方式使用cbind(),尽管我知道这行不通。
lapply(ana, function(x) cbind(x, new = names(ana)))
#$rome
# time temperature new
#1 2014-09-01 19 rome
#2 2014-09-02 21 paris
#3 2014-09-03 17 rome
#
#$paris
# time temperature new
#1 2014-09-01 18 rome
#2 2014-09-02 12 paris
#3 2014-09-03 17 rome
我感觉setNames() 可能会提供一些东西,而且这可以通过简单的方式完成。不过,我可能是错的。非常感谢您抽出宝贵时间。
【问题讨论】:
-
plyr::ldply(ana)应该会让你继续前进。我很确定在 SO 的某个地方有一个很好的答案,还有base解决方案。 -
@Henrik 感谢您的支持。我将进一步寻找关于 SO 的帖子,同时我会使用
ldply寻求解决方案。 -
@Roland 非常感谢您的解决方案。我试图避免
for循环。但是,你在这里教会了我好东西。谢谢。 -
@Henrik 是的,链接给了我答案。我对
ldply视而不见。谢谢你让我知道链接。我找不到它。