Jim O.
Jim O.

Reputation: 1111

store variable name as corresponding column values

Consider the following:

x <- c("a", "b", "c", "d" , "e", "f")
y <- c("N", "M")
z <- c("P", "Q")

The final product I want:

A B
x a
x b
x c
x d
x e
x f
y N
y M
z P
z Q  

Here is what I have tried so far

rbind(x, y, z)
data.frame(c(x, y, z))
cbind(x, y, z)
stack(x, y, z)
merge(x, y, z)

Upvotes: 2

Views: 51

Answers (4)

akrun
akrun

Reputation: 886948

Here is an option with tidyverse

library(tidyverse)
mget(letters[24:26]) %>%
   enframe %>% 
   unnest
# A tibble: 10 x 2
#   name  value
#   <chr> <chr>
# 1 x     a    
# 2 x     b    
# 3 x     c    
# 4 x     d    
# 5 x     e    
# 6 x     f    
# 7 y     N    
# 8 y     M    
# 9 z     P    
#10 z     Q    

Note that by default enframe gives the column names as "name" and "value", but the names can be changed by specifying the arguments to the custom names

mget(letters[24:26]) %>%
    enframe(name = "A", value = "B") %>% 
    unnest

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520938

Using expand.grid with rbind:

df <- rbind(expand.grid("x", x), expand.grid("y", y), expand.grid("z", z))
names(df) <- c("A", "B")
df

   A B
1  x a
2  x b
3  x c
4  x d
5  x e
6  x f
7  y N
8  y M
9  z P
10 z Q

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388817

Another option is to add all the variables in a list and then create a dataframe.

lst <- list(x = x, y = y, z = z)
data.frame(A = rep(names(lst), lengths(lst)), B = unlist(lst), row.names = NULL)

#   A B
#1  x a
#2  x b
#3  x c
#4  x d
#5  x e
#6  x f
#7  y N
#8  y M
#9  z P
#10 z Q

Upvotes: 1

thelatemail
thelatemail

Reputation: 93813

stack is what you want, except using a named list:

stack(list(x=x,y=y,z=z)) #or
stack(mget(c("x","y","z")))

#   values ind
#1       a   x
#2       b   x
#3       c   x
#4       d   x
#5       e   x
#6       f   x
#7       N   y
#8       M   y
#9       P   z
#10      Q   z

Upvotes: 2

Related Questions