简体   繁体   中英

Convert data.frame columns to vectors

Two different ways to create data.frame lead to 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 to warning:

[1] NA
Warning message:
In mean.default(df2$a) : argument is not numeric or logical: returning NA

I encounter this problem when parsing a json file into data.frame , I found that I made a mistake assuming that a column of data.frame is always vector , but it could be list instead. When it's a list , not only mean , many other functions like summary and as.Date won't work as expected. So now the data type data.frame are no longer "safe" to me, passing data.frame as input without knowing how it is created means I need to convert its columns to vector explicitly, and there might be more complicated issue where list and vector coexist:

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

So I tried to convert all columns to vector :

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

But I found it too verbose, are there any 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM