如何使用列表中的名称创建新列 [英] How to create a new column with names in a list
问题描述
我已经在网上搜索帖子,以找到解决方案.但是,我什么也找不到.因此,我决定寻求您的帮助.我有一个带有数据框的列表.我从每个数据框中选择了某些列,并将它们组合在一起.当我合并来自两个数据帧的数据时,我想添加一列,其中包括列表的名称.但是,我无法实现这一目标.这是示例数据以及我尝试过的内容.
I have searched posts on web to find a solution. But, I could not identify any. Therefore, I decided to ask your help. I have a list with data frames. I chose certain columns from each data frame and combine them. When I was combining data from two data frames, I wanted to add a column which includes the names of the list. But, I could not achieve this. Here are a sample data and what I have tried.
样本数据和我的尝试
### 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))
我想在此处添加一些内容,以便使用新列(位置)创建以下理想结果.请注意,我修剪了理想的结果以节省空间.
I wanted to add something here to create the following ideal outcome with the new column, location. Please note that I trimmed the ideal outcome to save space.
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()
,尽管我知道这是行不通的.
One thing I tried was to use cbind()
in the following way although I knew this would not work.
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()
可以提供某些东西,并且可以通过简单的方式完成.我可能是错的.非常感谢您抽出宝贵的时间.
I have the feeling that setNames()
may offer something, and that this can be done in a simple way. I could be wrong, though. Thank you very much for taking your time.
推荐答案
您可以
ana <- Map(cbind, ana, location = names(ana))
在调用rbind.fill
之前附加location
列.
这篇关于如何使用列表中的名称创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!