简体   繁体   English

将一列作为数据框列表添加到数据框

[英]Add a column to data frame as a list of data frames

Just wondering how can I add a new column to an existing data frame which is a list of data frames.只是想知道如何向现有数据框添加新列,该数据框是数据框列表。 For example, if I have a data frame like so:-例如,如果我有这样的数据框:-

x <- data.frame("SN" = 1:2, "Age" = c(21,15), "Name" =
c("John","Dora"))

I need to add a new column to it say 'test' - which I can realize by我需要在其中添加一个新列,比如“测试”——我可以通过

x$test <- 1

But this adds a new column as a numeric column.但这会添加一个新列作为数字列。

I need this column such that the element in each row of this column in this data frame is a list of say three (3) data frames.我需要此列,以便此数据框中此列的每一行中的元素是三 (3) 个数据框的列表。 Each of these 3 data frame in a row will contain different number of rows and columns.一行中的这 3 个数据帧中的每一个都将包含不同数量的行和列。 Similar data frames in other rows will contain same number type of columns but can have different number of rows.其他行中的类似数据框将包含相同数量类型的列,但可以具有不同数量的行。

Like this:-像这样:-

x$test[1] <- list(df1_1, df1_2, df1_3)
x$test[2] <- list(df2_1, df2_2, df2_3)

where df1_1, df1_2, df1_3 are independent data frames with different number of columns and rows in row 1 and df2_1, df2_2, df2_3_3 are independent data frames with different number of columns and rows in row 2.其中 df1_1、df1_2、df1_3 是第 1 行具有不同列数和行数的独立数据帧,而 df2_1、df2_2、df2_3_3 是第 2 行具有不同列数和行数的独立数据帧。

The number of columns and the data type of these columns of df1_1 and df2_1 are the same. df1_1 和 df2_1 的列数和这些列的数据类型相同。 Similarly, the number of columns and the data type of these columns of df1_2 and df2_2 are the same and so on.同样,df1_2 和 df2_2 的这些列的列数和数据类型相同,依此类推。

Is there a way to do so?有没有办法这样做?

The generation of the data frames df1_1, df1_2, df1_3 are done through a loop.数据帧 df1_1、df1_2、df1_3 的生成是通过循环完成的。

Any pointers/suggestions shall be highly valued.任何指针/建议都应受到高度重视。

Best regards此致

Deepak Agarwal迪帕克·阿加瓦尔

We could get the datasets into a list with mget我们可以使用mget将数据集放入一个list

# // initialize a list column
x$test <- vector('list', nrow(x))
# // loop over the sequence of rows of dataset
for(i in seq_len(nrow(x))) {
     # // create string with index
     str1 <- paste0('df', i, '_', 1:3)
     # // get the value of the objects from string with mget
     tmplist <- mget(str1)
     # // assign it to the corresponding list element of test
     x$test[[i]] <- tmplist
  }             

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

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