[英]Merge dataframes of list and obtain names of dataframes as column
I merged all data frames from a list in just one data frame. 我将列表中的所有数据框合并为一个数据框。
The dataframes inside the list are called 列表内的数据框称为
TAI
NAM
HEE
and each data frame looks like this 每个数据框看起来像这样
Yr-M Compound1 Compound 2
2015-01 0.002 0.15
2015-02 0.004 0.02
2015-03 0.01 0.09
when I merge all dataframes with meanall<-do.call(rbind, meaneach)
I get 当我将所有数据meanall<-do.call(rbind, meaneach)
与meanall<-do.call(rbind, meaneach)
合并时meanall<-do.call(rbind, meaneach)
我得到
Yr-M Compound1 Compound2
TAI.1 2015-01 0.002 0.15
TAI.2 2015-02 0.004 0.02
TAI.3 2015-03 0.01 0.09
.
.
.
NAM.1 2015-01 0.03 0.4
NAM.2 2015-02 0.001 0.005
I would like to get a column with the names of the list and not as rownames (like above), and without the numbers (TAI.1, TAI.2...), I just want the name TAI 我想获得一列带有列表名称而不是行名的列(如上),并且没有数字(TAI.1,TAI.2 ...),我只想要名称TAI
So that I get this: 这样我得到:
List Yr-M Compound1 Compound2
TAI 2015-01 0.002 0.15
TAI 2015-02 0.004 0.02
TAI 2015-03 0.01 0.09
.
.
.
NAM 2015-01 0.03 0.4
NAM 2015-02 0.001 0.005
How can I do this? 我怎样才能做到这一点?
Rownames you can not have duplicates. 行名不能重复。 So the best thing to do is convert the rownames to a column and then use gsub to remove the .[0-9], ie 因此,最好的办法是将行名转换为列,然后使用gsub删除。[0-9],即
df <- do.call(rbind, your_list)
df$list_id <- gsub('\\..*', '', rownames(df))
Note that you can use dplyr
or data.table
version of rbinding a list which have the option of including the list names as a column, ie 请注意,您可以使用dplyr
或data.table
版本的绑定列表,可以选择将列表名称作为列包括在内,即
dplyr::bind_rows(your_list, .id = 'list_id')
data.table::rbindlist(your_list, idcol = 'list_id')
You can add an additional column with the listnames after merging the three lists via do.call
: 您可以通过do.call
合并三个列表后,使用列表名称添加一个附加列:
nameColumn <- data.frame(listName = c(rep(c('TAI','NAM','HEE'),
c(length(TAI),length(NAM),length(HEE) ))
meanall <- cbind(meanall, nameColumn)
If you want the nameColumn
to be the first column, just switch arguments in cbind
to 如果希望将nameColumn
作为第一列,只需将cbind
中的参数cbind
为
meanall <- cbind(nameColumn, meanall)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.