0

I Have this data.base in class list in R.

$multiinstrumentais
[1] "248269" "248827"

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

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

I want to Transform in something like this in data.frame:

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

2 Answers2

1

Maybe there's a more elegant way, but this will do fine:

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

This uses lapply to iterate over the list elements, binding the multiple of the element name and the respective values in a dataframe together.

do.call(rbind, combines everything into a single dataframe.

Val
  • 6,585
  • 5
  • 22
  • 52
1

This can actually be done with stack from base R:

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

Here's another solution with dplyr and tibble, though this adds a number to the end of the row name, you can remove it by adding mutate(rowname = str_remove(rowname, pattern = '[[:digit:]]+')) to the chain:

library(tibble)
library(dplyr)

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

Returns:

# 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

Or with tidyr and dplyr, this seems to work:

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

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

Using Val's data:

lst<- list(
  multiinstrumentais=c("248269","248827"),
  geds=c("248198","248198","248857"),
  ghzmb=c("248087","296994","302862")
)
tyluRp
  • 4,678
  • 2
  • 17
  • 36