简体   繁体   English

如何将带有向量列的行附加到R中的数据帧

[英]How to append a row with a vector column to a data frame in R

Here is an example, 这是一个例子

df <- data.frame(x = I(list(1:2, 3:4)))
x <- df[1,]

Now the following does not work, 现在以下内容不起作用,

    df[2,] <- x 

or 要么

    df[2,] <- I(x)


 Warning message:
  In `[<-.data.frame`(`*tmp*`, 2, , value = list(1:2)) :
  replacement element 1 has 2 rows to replace 1 rows

How do I add more rows to data frame with a single column of vector type. 如何使用向量类型的单列将更多行添加到数据框中。

I found the following after few tries, 经过几次尝试,我发现了以下内容,

df[2,] <- list(x)

add new row of list type. 添加列表类型的新行。

It might be because you are using a list. 可能是因为您使用的是列表。 If you set your data frame as: 如果将数据框设置为:

df <- data.frame(rbind(c(1, 2), c(3, 4)))

then your code should work: 那么您的代码应该可以工作:

df <- data.frame(rbind(c(1, 2), c(3, 4))) # Make DF
x <- df[1,]
df[2,] <- x

print(df)

> df
  X1 X2
1  1  2
2  1  2

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

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