I have to cope with an ugly list called ul
that looks like this:
[[1]]
[[1]]$param
name value
"Section" "1"
[[1]]$param
name value
"field" "1"
[[1]]$param
name value
"final answer" "1"
[[1]]$param
name value
"points" "-0.0"
[[2]]
[[2]]$param
name value
"Section" "1"
[[2]]$param
name value
"field" "2"
[[2]]$param
name value
"final answer" "1"
[[2]]$param
name value
"points" "1.0"
[[3]]
[[3]]$param
name value
"Section" "1"
[[3]]$param
name value
"field" "3"
[[3]]$param
name value
"final answer" "0.611"
[[3]]$param
name value
"points" "1.0"
I would like to convert the list to a simple data frame, i.e.
Section field final answer points
1 1 1 -0.0
1 2 1 1.0
1 3 0.611 1.0
Is there any straightforward way to achieve that? or do I have to make a function accessing each list individually and binding it to a dataframe?
The data is imported from an uglier xml file, so if someone wants to play with it there is a link to the RData file. Sorry for not having reproducible code. Thank you very much.
Convert List to DataFrame using data. data. frame() is used to create a DataFrame in R that takes a list, vector, array, etc as arguments, Hence, we can pass a created list to the data. frame() function to convert list to DataFrame. It will store the elements in a single row in the DataFrame.
Output: Now to add a list as a column, create a list with required values. Then, use the name of the data frame and the new column separated by $ and assign this to the list so created. This will assign the list to the column name given and then add it to the dataframe.
There is probably a better solution, but this should get you started. First, we load some libraries
R> library(plyr)
R> library(reshape2)
Then handle your lists in two parts.
##lapply applies ldply to each list element in turn
ul1 = lapply(ul, ldply)
##We then do the same again
dd = ldply(ul1)[,2:3]
Next we label output according to their list order
R> dd$num = rep(1:3, each=4)
Then we convert from long to wide format
R> dcast(dd, num ~ name)
num field final answer points Section
1 1 1 1 -0.0 1
2 2 2 1 1.0 1
3 3 3 0.611 1.0 1
An answer to a similar problem was given by Marc Schwartz at this link : https://stat.ethz.ch/pipermail/r-help/2006-August/111368.html
I'm copying it in case the link is deleted.
as.data.frame(sapply(a, rbind))
V1 V2 V3
1 a b c
2 1 3 5
3 2 4 6
or:
as.data.frame(t(sapply(a, rbind)))
V1 V2 V3
1 a 1 2
2 b 3 4
3 c 5 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With