2016-08-06 4 views
2

リストlには、それぞれ1つ、2つ、3つの名前の3つの文字列があります。 lをデータフレームに変換したいのですが、名前がnである追加の列が必要です。リストをRのデータフレームに変換し、サブリストの名前を持つ列を追加します。

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

これはループを使用して行うことができますが、これを行うにはより効率的な方法があると確信しています。

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 

答えて

4

別のオプションは、ベクトルであることがリストの各要素の名前を設定した後stackを使用することである。

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

ベースRを使用すると、本質的に2行で行うことができます。

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

他の同様の基地Rオプション:

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

別のオプションmeltから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 

かと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 
関連する問題