user2799980
user2799980

Reputation: 21

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.

Upvotes: 1

Views: 459

Answers (2)

user2799980
user2799980

Reputation: 21

I found the following after few tries,

df[2,] <- list(x)

add new row of list type.

Upvotes: 1

afusco
afusco

Reputation: 1

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

Upvotes: 0

Related Questions