简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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