Home > Software engineering >  How can I dynamically assign variable names within a function in data.table in R?
How can I dynamically assign variable names within a function in data.table in R?

Time:02-03

I have some data on concentrations observed for chemicals by tasks performed. There are three people, each performing two tasks, and repeating each task twice. concentrations are measured simultaneously for the three different chemicals, at five time points. Person A has only completed two repetitions, and some other concentrations were missing. The data looks like this:

    test_dt <- data.table(person = rep(LETTERS[1:3],each = 20),
           task = rep(LETTERS[24:25], each = 10),
           reps = rep(c(1,2),each = 5),
           time = 1:5, chem1 = rnorm(60,1,0.2),
           chem2 = rnorm(60,4,1.1),chem3 = rnorm(60,2,0.75))
   test_dt[person == "A" & reps == 2,`:=`(chem3 = NA_real_)]
   test_dt[person == "B" & task == "X" & reps == 1 &time %in% 3:5,chem1 := NA_real_]
   test_dt[person == "C" & task == "Y" & reps == 2 &time %in% 3:4,chem2 := NA_real_]
   

I want to get the time when the data is first NA and the time NAs end, for each person, by task and repetition. I tried doing this:

lapply(c("chem1","chem2","chem3"),function(var){
  start_var = paste0("na_start_",var)
  end_var = paste0("na_end_",var)
  test_dt[is.na(get(var)), 
          .(deparse(substitute(start_var)) = min(time),
            deparse(substitute(end_var)) = max(time)),
          .(person,task,reps)]
})

But ended up with this error:

"  test_dt[is.na(get(var)), 
          .(deparse(substitute(start_var)) ="
>             deparse(substitute(end_var)) = max(time)),
Error: unexpected ')' in "            deparse(substitute(end_var)) = max(time))"
>           .(person,task,reps)]
Error: unexpected ']' in "          .(person,task,reps)]"
> })
Error: unexpected '}' in "}"

How can I do this in data.table in R?

CodePudding user response:

Instead of deparse/substitute, use setNames or setnames. Note that = wouldn't allow evaluation on the lhs

lapply(c("chem1","chem2","chem3"),function(var){
  start_var = paste0("na_start_",var)
  end_var = paste0("na_end_",var)
 test_dt[is.na(get(var)), setNames(.(min(time), max(time)),
     c(start_var, end_var)), .(person, task, reps)]
})

-output

[[1]]
   person task reps na_start_chem1 na_end_chem1
1:      B    X    1              3            5

[[2]]
   person task reps na_start_chem2 na_end_chem2
1:      C    Y    2              3            4

[[3]]
   person task reps na_start_chem3 na_end_chem3
1:      A    X    2              1            5
2:      A    Y    2              1            5
  • Related