'Change df columns from lists to vectors

I've been using R for a while, but lists perplex me.

For some reason in some cases my function outputs a data frame of lists:

str() returns something like:

    *'data.frame':  4683 obs. of  6 variables:  
     $ f1:List of 4683  
      ..$ : num -0.196  
      ..$ : num -0.205  
      ..$ : num -0.209  
      ..$ : num -0.218  
      ..$ : num -0.197  
      ..$ : num -0.136  
      ..$ : num -0.22*  

instead of

*'data.frame':  4683 obs. of  6 variables:  
 $ f1: num  -0.197 -0.205 -0.208 -0.218 -0.197 ...  
 $ f2: num  -0.13 -0.139 -0.136 -0.137 -0.126 ...  
 $ f3: num  -0.216 -0.221 -0.214 -0.209 -0.203 ...  
 $ f4: num  0.00625 -0.04806 -0.04888 -0.02979 -0.03813 ...  
 $ f5: num  -0.15 -0.178 -0.173 -0.207 -0.154 ...  
 $ f6: num  -0.191 -0.224 -0.25 -0.183 -0.209 ...*  
...

like I'd expect. Is there some simple way to convert df from the first case to the second? I have tried manually casting columns as vectors, which not only doesn't work, but also would not be very effective.



Solution 1:[1]

When we have a data frame like this

df
# 1 1, 2, 3 1, 2, 3
# 2 4, 5, 6 4, 5, 6

where

df |> str()
# 'data.frame': 2 obs. of  2 variables:
# $ :List of 2
#  ..$ : int  1 2 3
#  ..$ : int  4 5 6
# $ :List of 2
#  ..$ : int  1 2 3
#  ..$ : int  4 5 6

we can do

r <- do.call(data.frame, df)
r
#   X1.3 X4.6 X1.3.1 X4.6.1
# 1    1    4      1      4
# 2    2    5      2      5
# 3    3    6      3      6

where

str(r)
# 'data.frame': 3 obs. of  4 variables:
# $ X1.3  : int  1 2 3
# $ X4.6  : int  4 5 6
# $ X1.3.1: int  1 2 3
# $ X4.6.1: int  4 5 6

Explanation: do.call constructs a data.frame() call with df (which is a "data.frame" as well as a "list") as ... arguments. So in our df with two lists of length 2, we get two data frames with 2 columns, i.e. a resulting data frame with 4 columns in this case.

By the way, you can use Reduce(.) just as well.


Data:

df <- structure(list(list(1:3, 4:6), list(1:3, 4:6)), names = c("", 
""), class = "data.frame", row.names = c(NA, -2L))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1