maryam maryam - 3 months ago 8
R Question

R combine character vectors into dataframe, with vector name as row id

I have three character vectors:

blue <-c("Ti","Ka","Vv","Cn")
Turq <-c("Cc","Wx","Oq","Yt")
Indigo <-c("Gb","Ap")


and I want to combine them into one dataframe so that they look like this:

blue Ti
blue Ka
blue Vv
blue Cn
Turq Cc
Turq Wx
Turq Oq
Turq Yt
Indigo Gb
Indigo Ap


I cannot seem to find a way

Answer

You can put the vectors in a named list and then use stack:

lst <- list(blue = blue, Turq = Turq, Indigo = Indigo)
lst
# $blue
# [1] "Ti" "Ka" "Vv" "Cn"

# $Turq
# [1] "Cc" "Wx" "Oq" "Yt"

# $Indigo
# [1] "Gb" "Ap"

stack(lst)
#   values    ind
#1      Ti   blue
#2      Ka   blue
#3      Vv   blue
#4      Cn   blue
#5      Cc   Turq
#6      Wx   Turq
#7      Oq   Turq
#8      Yt   Turq
#9      Gb Indigo
#10     Ap Indigo
Comments