r - Convert data.frame columns to vectors -


two different ways create data.frame lead different result:

a <- c(1,2) b <- c(3,4) df1 <- as.data.frame(cbind(a, b)) df1 str(df1) mean(df1$a) 

this works fine but:

a <- list(1,2) b <- list(3,4) df2 <- as.data.frame(cbind(a, b)) df2 str(df2) mean(df2$a) 

leads warning:

[1] na warning message: in mean.default(df2$a) : argument not numeric or logical: returning na 

i encounter problem when parsing json file data.frame, found made mistake assuming column of data.frame vector, list instead. when it's list, not mean, many other functions summaryand as.date won't work expected. data type data.frame no longer "safe" me, passing data.frame input without knowing how created means need convert columns vector explicitly, , there might more complicated issue list , vector coexist:

df3 <- df2 df3$a <- as.numeric(df3$a) str(df3) 

so tried convert columns vector:

data.frame(lapply(df3, function(x) {if (is.list(x)) do.call(c, x) else x})) 

but found verbose, there better solutions?

you can try:

data.frame(lapply(df3, unlist)) 

produces:

'data.frame': 2 obs. of  2 variables:  $ a: num  1 2  $ b: num  3 4 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -