我有一些按所执行任务观察到的化学品浓度数据。有三个人,每人执行两项任务,每项任务重复两次。在五个时间点同时测量三种不同化学品的浓度。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中执行此操作?
1条答案
按热度按时间myzjeezk1#
使用
setNames
或setnames
代替deparse/substitute
。注意,=
不允许在lhs上求值