Reputation: 6842
I would like to have multiple elements per cell in a particular column of a data frame. There is a note at R-bloggers explaining how to do so with lists:
> d <- data.frame(id=1:2)
> d$name <- list(c("Bond", "James"),c("Poppins", "Mary"))
> d
id name
1 1 Bond, James
2 2 Poppins, Mary
So far so good. But now I would like to add further rows to the data frame. This is the result:
> d[nrow(d) + 1,] <- list(3, c("Hood", "Robin"))
Warning message:
In `[<-.data.frame`(`*tmp*`, nrow(d) + 1, , value = list(3, c("Hood", :
replacement element 2 has 2 rows to replace 1 rows
> d
id name
1 1 Bond, James
2 2 Poppins, Mary
3 3 Hood
The second element of the vector is discarded. How can I convince R to add the second element to the name cell too?
Upvotes: 1
Views: 463
Reputation: 887251
We can use add_row
library(tibble)
add_row(d, id = 3, name = list(c('Bond', 'Robbin')))
# id name
#1 1 Bond, James
#2 2 Poppins, Mary
#3 3 Bond, Robbin
Regarding the way to assign next row, we have a list
of list
as the 2nd column
d[nrow(d) + 1, ] <- list(3, list(c("Hood", "Robbin")))
d
# id name
#1 1 Bond, James
#2 2 Poppins, Mary
#3 3 Hood, Robbin
Upvotes: 1