简体   繁体   English

在R中,使用df名称将NEW列添加到MULTIPLE df

[英]In R, add NEW column to MULTIPLE df using df names

I am new to R so this is a beginner question. 我是R的新手,所以这是一个初学者的问题。

Currently I have quite a number of data frames from different companies, lets call them a, b, c, d, e, f... 目前我有来自不同公司的大量数据框,我们称之为a, b, c, d, e, f...

I am trying to: 我在尝试着:

(1) add one column to each data frame with value equals to the data frame name (I have previously read & named each df from its csv file according to the company) (1)向每个数据帧添加一列,其值等于数据帧名称(我之前已经根据公司从其csv文件中读取并命名了每个df)

(2) combine all of them into one big data frame (2)将所有这些组合成一个大数据帧

The result would look similar to: 结果看起来类似于:

    col1    col2    new_col
1     1       1       a
2     3       4       a
...
100   1       2       b
101   4       5       b
...
992   3       4       f
993   4       5       f
...

I have tried: 我努力了:

    companies <- list(a, b, c, d, e)
    companies_name <- list("a", "b", "c", "d", "e")
    companies_all <- Map(cbind, companies, company <- companies_name)

but this returned a list of lists. 但是这返回了一个列表列表。 Is there a more elegant way to accomplish this? 是否有更优雅的方式来实现这一目标? Please help! 请帮忙!

Thank you! 谢谢!


This addressed a somewhat similar question but somehow I could not apply the code. 这解决了一个类似的问题,但不知怎的,我无法应用代码。 r function/loop to add column and value to multiple dataframes r function / loop将列和值添加到多个数据帧

a <- data.frame(col1 = 1:4, col2 = 5:8)
b <- data.frame(col1 = 11:14, col2 = 15:18)

ldfs <- list(a = a, b = b)
for (df_name in names(ldfs))
  ldfs[[df_name]][["new_col"]] <- df_name
df <- do.call(rbind, ldfs)
rownames(df) <- NULL

output: 输出:

> df
  col1 col2 new_col
1    1    5       a
2    2    6       a
3    3    7       a
4    4    8       a
5   11   15       b
6   12   16       b
7   13   17       b
8   14   18       b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM