Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert list to dataframe with special format in R

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading