user3684014
user3684014

Reputation: 1185

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 summaryand 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?

Upvotes: 2

Views: 165

Answers (1)

BrodieG
BrodieG

Reputation: 52687

You can try:

data.frame(lapply(df3, unlist))

Produces:

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

Upvotes: 3

Related Questions