applying a function to a list of data frames in R

后端 未结 1 894
面向向阳花
面向向阳花 2021-01-28 15:57

I\'d like to apply acast () to a list of data frames and return a new list of matrices.

list<-list(df1 = data.frame(vegspecies=c(\"vsp1\", \"vsp1\", \"vsp1\"         


        
相关标签:
1条回答
  • 2021-01-28 16:46

    We can use lapply to loop over the list of 'data.frames and apply theacast` (assuming that 'df2' is also a similar dataset as 'df1' with same column names, types etc.)

    res <- lapply(lst, function(x) acast(x, vegspecies ~ species, fill=0))
    

    NOTE: It is better not to name a list object "list" (similarly a vector as "vector" or data.frame as "data.frame"). It can be any other name.


    However, we can still use a single acast on a single data.frame by rbinding the lst object with a 'id' column to identify the list element

    library(data.table)
    dt <- rbindlist(lst, idcol="grp")
    dcast(dt, grp + vegspecies ~ species, fill = 0)
    
    0 讨论(0)
提交回复
热议问题