2016-08-06 10 views
2

Liste l hat drei Strings, die einen, zwei bzw. drei Namen haben. Ich möchte l in einen Datenrahmen konvertieren, und ich brauche eine zusätzliche Spalte mit den Namen in n.Liste in Datenrahmen in R konvertieren und Spalte mit Namen von Unterlisten hinzufügen

l <- list(c("a", "b"), c("c", "d", "e"), c("e")) 
n <- c("one", "two", "three") 

Ich kann es mit einer Schleife, aber ich bin mir sicher, es gibt effizientere Möglichkeiten, dies zu tun.

out <- NULL 
for (i in 1:length(n)){ 
    step <- rep(n[i], length(l[[i]])) 
    out <- c(out, step)} 

df <- as.data.frame(unlist(l)) 
df$n <- out 
df 

# unlist(l)  n 
#1   a one 
#2   b one 
#3   c two 
#4   d two 
#5   e two 
#6   e three 

Antwort

4

Eine weitere Option ist stack zu verwenden, nachdem Sie den Namen für jedes Element der Liste Einstellung der Vektor zu sein:

stack(setNames(l, n)) 

# values ind 
#1  a one 
#2  b one 
#3  c two 
#4  d two 
#5  e two 
#6  e three 
4

Mit Base R können Sie es im Wesentlichen in zwei Zeilen tun.

l <- list(c("a", "b"), c("c", "d", "e"), c("e")) 
n <- c("one", "two", "three") 

#Create an appropriately sized vector of names 
nameVector <- unlist(mapply(function(x,y){ rep(y, length(x)) }, l, n)) 

#Create the result 
resultDF <- cbind.data.frame(unlist(l), nameVector) 


> resultDF 
    unlist(l) nameVector 
1   a  one 
2   b  one 
3   c  two 
4   d  two 
5   e  two 
6   e  three 
3

Eine weitere ähnliche Basis R Option:

do.call(rbind, Map(f = expand.grid, l = l, n = n, stringsAsFactors = F)) 
# l  n 
# 1 a one 
# 2 b one 
# 3 c two 
# 4 d two 
# 5 e two 
# 6 e three 
1

Eine weitere Option ist melt von reshape2

library(reshape2) 
melt(setNames(l, n)) 
# value L1 
#1  a one 
#2  b one 
#3  c two 
#4  d two 
#5  e two 
#6  e three 

Oder mit base R

data.frame(value = unlist(l), key = rep(n, lengths(l))) 
# value key 
#1  a one 
#2  b one 
#3  c two 
#4  d two 
#5  e two 
#6  e three