Home > OS >  how to convert list to dataframe with special format in R
how to convert list to dataframe with special format in R

Time:04-09

so i have a list that looks like

my_list
[[1]]
     "a" "b"
[[2]]
     "c"  

#corresponding to time vector 
time
2000 2001

and i also know the factor vector

factor
'a' 'b' 'c' 'd'

How to I convert this list to a dataframe that looks like:

year  on_off  factor
2000   TRUE     a
2000   TRUE     b
2000   FALSE    c
2000   FALSE    d
2001   FALSE    a
2001   FALSE    b
2001   TRUE     c
2001   FALSE    d

thanks in advance!

CodePudding user response:

Perhaps this helps

out <- do.call(rbind, Map(cbind, year = 2000:2001, 
  lapply(my_list, \(x) as.data.frame(table(factor(x, levels = letters[1:4]))))))
names(out)[2:3] <- c("values", "on_off")
out$on_off <- as.logical(out$on_off)

-output

> out
  year values on_off
1 2000      a   TRUE
2 2000      b   TRUE
3 2000      c  FALSE
4 2000      d  FALSE
5 2001      a  FALSE
6 2001      b  FALSE
7 2001      c   TRUE
8 2001      d  FALSE

data

my_list <- list(c("a", "b"), "c")
  • Related