2017-08-18 3 views
3

に、これはすべてのリストから最初の列は、データを対応する、それに応じて転置されるべきであり、このトランスポーズリストの行データフレーム

 level1 level2 level3 level4 level5 level6 level7 
1)  18  abc  NA  pqr  lmn  NA  NA 
2)  20  xyz  hive NA  foo  bar  NA 
3)  22  NA  dark yellow foobar blue NA 
4)  24  dvd  dxs  NA  glass while though 

のようなO/Pの何かを期待

lst=list(structure(c("level1", "level2", "level4", "level5","18", "abc", "pqr", "lmn"), 
     .Dim = c(4L, 2L)), 
    structure(c("level1", "level2", "level3", "level5", "level6", "20", "xyz", "hive", "foo", "bar"), 
     .Dim = c(5L, 2L)), 
    structure(c("level1", "level3", "level4", "level5","level6", "22", "dark", "yellow","foobar", "blue"), 
     .Dim = c(5L, 2L)), 
    structure(c("level1", "level2", "level3", "level5","level6","level7","24", "dvd", "dxs","glass", "while","though"), 
    .Dim = c(6L, 2L)) 
    ) 

私のリスト構造であると仮定彼らの行を見上げる必要があります。コラム自体与えるエラーも

apply(list_temp,1,function(x){list_temp[[x]][,1]}) 

で試してみました

unique(t(list_temp[[c(1,2)]][,1])) 
ERROR:Error in list_temp[[c(1, 2)]][, 1] : incorrect number of dimensions 

にすべての行の転置をやろうとしている。しかし

は私に

Error in apply(list_temp, 1, function(x) { : 
    dim(X) must have a positive length 

を与え、それがどうあるべきか上の任意の提案完了しました。

ありがとうございました。

答えて

4

二つのアプローチ:

1)ではdata.tableパッケージ

を使用して:

library(data.table) 
dcast(rbindlist(lapply(lst, as.data.table), idcol = 'id'), 
     id ~ V1, value.var = 'V2')[, id := NULL][] 

は、あなたが得る:

level1 level2 level3 level4 level5 level6 level7 
1:  18 abc  NA pqr lmn  NA  NA 
2:  20 xyz hive  NA foo bar  NA 
3:  22  NA dark yellow foobar blue  NA 
4:  24 dvd dxs  NA glass while though 
塩基R

を使用して10

2):

reshape(transform(do.call(rbind.data.frame, lst), 
        r = rep(seq_along(lst), lengths(lst)/2)), 
     idvar = 'r', timevar = 'V1', direction = 'wide')[,-1] 

は、あなたが得る:ここで

V2.level1 V2.level2 V2.level4 V2.level5 V2.level3 V2.level6 V2.level7 
1   18  abc  pqr  lmn  <NA>  <NA>  <NA> 
5   20  xyz  <NA>  foo  hive  bar  <NA> 
10  22  <NA> yellow foobar  dark  blue  <NA> 
15  24  dvd  <NA>  glass  dxs  while though 
+0

... + 1 !!! – deepesh

+0

あなたのコードにいくつかのバグがあると思います。もし2つではなく4つのリストレコードを持っていれば、正しい出力は得られません。 – deepesh

+0

@deepesh質問にあなたの問題を再現する例を追加(追加)できますか? – Jaap

2

は移調、その後、データフレームをマージするReduceを使用して、別のアイデアです清掃をしてください。つまり、

0123あなたの時間と労力のためrbindlist..Thanksため与え

、とてもきれいでエレガントだった

level1 level2 level4 level5 level3 level6 level7 
1  18 abc pqr lmn <NA> <NA> <NA> 
2  20 xyz <NA> foo hive bar <NA> 
3  22 <NA> yellow foobar dark blue <NA> 
4  24 dvd <NA> glass dxs while though 
+2

また行く良いアプローチです..あなたの時間と労力のためにありがとう! – deepesh

関連する問題