简体   繁体   中英

R: data.table building a function out of multiple lapply statements

I am currently working in R using data.table and am trying to complete a list of data processing steps on a long list of data tables. I have got some separate lapply's and steps figured out, but I'm unsure of how to link the steps together into a function so that my list of data tables goes through each step and then comes out at the end combined using rbindlist.

Here are the data processing steps I'm working to complete: 1) subset all data tables down to one variable - "name" 2) convert each data table containing this one variable from long to wide 3) add a variable "data_set" that will hold the name of each table within it 4) combine data tables together into one large data table using rbindlist

Here's pieces of code that I have so far but am unsure how to piece together into one function, so that one list is passed from one step to the next:

    data_tables<-c("symp", "care", "meds")
    #1)subset out variable "name" from each data table
    one<-lapply(mget(data_tables),function(x)x[, .("name")])
    #2)convert from long to wide format - I'm unsure how to send the previous list "one" from the    
    last lapply to the next step
    dt<-dt[, as.list(table(name))]
    #3)add variable "data_set" containing name of each data set in list
    one_1 <- Map(function(x, nm) as.data.table(x)[, data_set := nm], mget(one), one)
    #4)combine list of data tables together using rbindlist
    combined<-rbindlist(one_1, use.names=TRUE, fill=TRUE, idcol=NULL)

My suggestion would be:

Create a function that does the complete steps for you as follows:

complete_work <- function(dt, nm){

step1 <- dt[, .("name")]
dt <- dt[, as.list(table(name))]
dt[, data_set := nm], step1 , step1)

}

Once you get your function to work for a specific data.table, use lapply:

lapply(list(symp, care, meds),  complete_work)

If you have an example of the input and the output, it would be easier to help you construct the answer you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM