以longdata格式转换data.frame中的列表[复制]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我在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
r list dataframe
2个回答
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
投票

这实际上可以通过基础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")
)
© www.soinside.com 2019 - 2024. All rights reserved.