以Longdata格式转换data.frame中的列表

时间:2018-03-02 13:30:00

标签: r list dataframe

我在R。

的班级列表中有这个data.base
$multiinstrumentais
[1] "248269" "248827"

$geds
[1] "248198" "248198" "248857"

$ghzmb
[1] "248087" "296994" "302862"

我想在data.frame中进行类似的转换:

words - cod 
multiinstrumentais - 248269
multiinstrumentais - 248827
geds - 248198
geds - 248198
geds - 248857
ghzmb - 248087
ghzmb - 296994
ghzmb - 302862

2 个答案:

答案 0 :(得分:1)

也许有一种更优雅的方式,但这样做会很好:

lst<- list(
  multiinstrumentais=c("248269","248827"),
  geds=c("248198","248198","248857"),
  ghzmb=c("248087","296994","302862")
)


df <- do.call(rbind,
lapply(seq_along(lst), function(ix) data.frame(words=rep(names(lst)[ix],length(lst[[ix]])),
                                              cod=lst[[ix]]))
)

#output

# > df
# words    cod
# 1 multiinstrumentais 248269
# 2 multiinstrumentais 248827
# 3               geds 248198
# 4               geds 248198
# 5               geds 248857
# 6              ghzmb 248087
# 7              ghzmb 296994
# 8              ghzmb 302862

这使用lapply迭代列表元素,将元素名称的多个和数据帧中的相应值绑定在一起。

do.call(rbind,将所有内容整合到一个数据框中。

答案 1 :(得分:1)

这实际上可以使用基础R中的stack完成:

stack(lst)

  values                ind
1 248269 multiinstrumentais
2 248827 multiinstrumentais
3 248198               geds
4 248198               geds
5 248857               geds
6 248087              ghzmb
7 296994              ghzmb
8 302862              ghzmb

这是另一个使用dplyrtibble的解决方案,虽然这会在行名称的末尾添加一个数字,但您可以通过向链中添加mutate(rowname = str_remove(rowname, pattern = '[[:digit:]]+'))来删除它:

library(tibble)
library(dplyr)

lst %>% 
  unlist() %>% 
  as.tibble() %>%
  rownames_to_column()

返回:

# A tibble: 8 x 2
  rowname             value 
  <chr>               <chr> 
1 multiinstrumentais1 248269
2 multiinstrumentais2 248827
3 geds1               248198
4 geds2               248198
5 geds3               248857
6 ghzmb1              248087
7 ghzmb2              296994
8 ghzmb3              302862

或者使用tidyrdplyr,这似乎有效:

lst %>% 
  unlist() %>% 
  bind_rows() %>% 
  gather()

# Alternatively, this one liner
tidyr::gather(bind_rows(unlist(lst)))

使用Val的数据:

lst<- list(
  multiinstrumentais=c("248269","248827"),
  geds=c("248198","248198","248857"),
  ghzmb=c("248087","296994","302862")
)