2

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))

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect. Thank you!
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.