Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

I know how to add a list column:

> df <- data.frame(a=1:3)

> df$b <- list(1:1, 1:2, 1:3)

> df

  a       b

1 1       1

2 2    1, 2

3 3 1, 2, 3

This works, but not:

> df <- data.frame(a=1:3, b=list(1:1, 1:2, 1:3))

Error in data.frame(1L, 1:2, 1:3, check.names = FALSE, stringsAsFactors = TRUE) : 

  arguments imply differing number of rows: 1, 2, 3

Why?

Also, is there a way to create df (above) in a single call to data.frame?

1 Answer

0 votes
by

According to R Documentation:

If a list or a data frame or matrix is passed to data.frame it is as if each component or column had been passed as a separate argument (except for matrices protected by I).

Therefore to pass a list as a data frame column, do the following:

> data.frame(a=1:3,b=I(list(1,1:2,1:3)))

  a       b

1 1       1

2 2    1, 2

3 3 1, 2, 3

Browse Categories

...