0

I have a named list whose each element is a character vector. I want to write this list into a single dataframe where I have two columns, one with the name of the character vector and the second column with each element of the character vector. Any help would be appreciated.

user1407875
  • 69
  • 1
  • 2
  • 4
  • 2
    It would help if you could illustrate this w/ a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), namely, a small sample dataset & what you want the output to look like. – gung - Reinstate Monica Aug 22 '13 at 17:46
  • Please post an example of output you are looking for. – Mayou Aug 22 '13 at 17:54

4 Answers4

1
 NewList <- lapply(names(List), function(X) data.frame(Names=X, Characters=List[[X]]))
 do.call(rbind, NewList)
Señor O
  • 17,049
  • 2
  • 45
  • 47
1

Maybe

data.frame(vecname = rep(names(ll), sapply(ll, length)), chars = unlist(ll))

to have each element of each list component correspond to a row in the final dataframe.

Ferdinand.kraft
  • 12,579
  • 10
  • 47
  • 69
1

I'm wondering if stack provides the functions you need (using the example of Henrik)

ll <- list(x1 = c("a", "b", "c"), x2 = c("d", "e"))
stack(ll)
#-------
  values ind
1      a  x1
2      b  x1
3      c  x1
4      d  x2
5      e  x2
IRTFM
  • 258,963
  • 21
  • 364
  • 487
0

A very straightforward way would be to use cbind(), like this:

cbind(names(l),l)

This will result in the following data frame, assuming that l = list(a="ax", b="bx"):

      l   
a "a" "ax"
b "b" "bx"

Of course, you can rename the columns and rows by adjusting the values in colnames(l) and rownames(l). In this example, the string names are automatically also applied to the rownames of the resulting data frame, so, depending on what you'd like to do with your data,

cbind(l)

might suffice, resulting in

  l   
a "ax"
b "bx"

Hope I could help.

maj
  • 2,479
  • 1
  • 19
  • 25
  • Of course, this is a solution for lists of character strings rather than character vectors. Sorry if that's not what you were looking for. – maj Aug 22 '13 at 18:17
  • If this is used with lists that have character vectors of length >1 then you get a matrix of lists. The phrase "lists of character strings" is unclear, but perhaps you meant lists of character vectors of length 1? (There is no "string" class in R.) – IRTFM Aug 22 '13 at 19:17
  • It simply took me a second to realize that in R, character combinations as in "word123" (this is what I meant by "strings") are not at all the same as vectors of individual characters. – maj Aug 22 '13 at 19:39
  • 1
    Correct. If you want to 'explode' a character vector element-by-element, then use `strsplit(vec, "")`. You get a list of things that might look like what you expected. – IRTFM Aug 22 '13 at 19:42