I have a list of data frame, for each list, I have a name for it, which is the USERID, the following is a sample of the list:
$'AAAAAA'
AA BB CC
a b 1
c d 2
e f 3
S'BBBBBB'
AA BB CC
g h 1
i j 2
k l 3
My question is how to convert this list into a data frame which has a new column showing the USERID, like the below sample:
AA BB CC USERID
a b 1 AAAAAA
c d 2 AAAAAA
e f 3 AAAAAA
g h 1 BBBBBB
i j 2 BBBBBB
k l 3 BBBBBB
Any Idea how it could be done. Thank you so much in advance
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.
tolist() to get a list of a specified column. From the dataframe, we select the column “Name” using a [] operator that returns a Series object. Next, we will use the function Series. to_list() provided by the Series class to convert the series object and return a list.
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.
Since cbind
recycles its arguments to the length of the longest vector, you could try
Reduce(rbind, Map(cbind, x, USERID = names(x)))
# AA BB CC USERID
# 1 a b 1 AAAAA
# 2 c d 2 AAAAA
# 3 e f 3 AAAAA
# 4 g h 1 BBBBB
# 5 i j 2 BBBBB
# 6 k l 3 BBBBB
where x
is
structure(list(AAAAA = structure(list(AA = c("a", "c", "e"),
BB = c("b", "d", "f"), CC = 1:3), .Names = c("AA", "BB",
"CC"), class = "data.frame", row.names = c(NA, -3L)), BBBBB = structure(list(
AA = c("g", "i", "k"), BB = c("h", "j", "l"), CC = 1:3), .Names = c("AA",
"BB", "CC"), class = "data.frame", row.names = c(NA, -3L))), .Names = c("AAAAA",
"BBBBB"))
Another way, using the development version of tidyr
:
# install.packages("devtools")
devtools::install_github("hadley/tidyr")
library(tidyr)
unnest(mylist, USERID)
# USERID AA BB CC
# 1 AAAAA a b 1
# 2 AAAAA c d 2
# 3 AAAAA e f 3
# 4 BBBBB g h 1
# 5 BBBBB i j 2
# 6 BBBBB k l 3
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