Reputation: 7879
I have multiple lists similar to those below.
a = c(1,2,3)
b = c(4,5,6)
c = c(7,8,9)
I know I can create a 3x3 dataframe using cbind.data.frame
. However, I would like to create a 2 column data frame, where rows 1-3 have a
in column 1, rows 4-6 have b
, etc. It would look like a data frame created manually from:
data.frame(c('a','a','a','b','b','b'), c(1,2,3,4,5,6))
Upvotes: 2
Views: 7733
Reputation: 70266
Another option is to create the 3x3 data.frame
and melt
it:
library(reshape2)
melt(data.frame(a = c(1,2,3),b = c(4,5,6),c = c(7,8,9)))
# variable value
#1 a 1
#2 a 2
#3 a 3
#4 b 4
#5 b 5
#6 b 6
#7 c 7
#8 c 8
#9 c 9
Upvotes: 3
Reputation: 887118
We can create a key/value
pair list
elements and use stack
to convert it to a 2 column dataset. The mget
gets the values of the character object names in a list
with key as the object names.
stack(mget(c('a', 'b', 'c')))
# values ind
#1 1 a
#2 2 a
#3 3 a
#4 4 b
#5 5 b
#6 6 b
#7 7 c
#8 8 c
#9 9 c
Upvotes: 4