如何在R的data.table中动态地分配函数内的变量名?

huus2vyu  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(86)

我有一些按所执行任务观察到的化学品浓度数据。有三个人,每人执行两项任务,每项任务重复两次。在五个时间点同时测量三种不同化学品的浓度。A只完成了两次重复,其他一些浓度缺失。数据如下所示:

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_]

我想通过任务和重复获得每个人的数据首次出现NA的时间和NA结束的时间。我尝试这样做:

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)]
})

但最后却出现了这样的错误:

"  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 "}"

如何在R中的data.table中执行此操作?

myzjeezk

myzjeezk1#

使用setNamessetnames代替deparse/substitute。注意,=不允许在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)]
})
  • 输出
[[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

相关问题