我在网上搜索帖子以找到解决方案。但是,我无法识别任何。因此,我决定寻求你的帮助。我有一个包含数据框的列表。我从每个数据框中选择了某些列并将它们组合起来。当我组合两个数据框中的数据时,我想添加一个包含列表名称的列。但是,我无法实现这一点。这是示例数据和我尝试过的内容。
示例数据和我的尝试
### 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()
可能会提供一些东西,并且这可以通过简单的方式完成。不过,我可能是错的。非常感谢您抽出宝贵时间。