r - Create a data.frame where a column is a list -


i curious know why following works:

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

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 

also, there way create df in single call data.frame?

slightly obscurely, ?data.frame:

if list or data frame or matrix passed ‘data.frame’ if each component or column had been passed separate argument (except matrices of class ‘"model.matrix"’ , protected ‘i’).

so

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

seems work.


Comments