r - 在 R 中的嵌套数据框中多次调用 ifelse

标签 r nested dataframe lapply

我有一个表单的数据框:

LociDT4Length
[[1]]
   Cohort  V1
1:    CEU 237
2:  Lupus 203
3:     RA 298
4:    YRI 278

[[2]]
   Cohort   V1
1:    CEU  625
2:  Lupus  569
3:     RA 1022
4:    YRI  762

[[3]]
   Cohort  V1
1:    CEU 161
2:  Lupus 203
3:     RA 268
4:    YRI 285

[[4]]
   Cohort   V1
1:    CEU 1631
2:  Lupus 1363
3:     RA 1705
4:    YRI 1887

前几天,我学会了命令:

with(LociDT4Length[[1]], ifelse(Cohort=="RA", V1/62,
                         ifelse(Cohort=="Lupus", V1/62,
                         ifelse(Cohort=="CEU", V1/96,
                         ifelse(Cohort=="YRI", V1/80,NA)))))

适本地返回结果:

[1] 2.468750 3.274194 4.806452 3.475000

但是,我尝试将此语句放入循环中,对每个嵌套的 DF 都返回了一个警告,并返回了不正确的结果。错误信息是:

1: In `[<-.data.table`(x, j = name, value = value) :
  Coerced 'double' RHS to 'integer' to match the column's type; may have 
  truncated precision. Either change the target column to 'double' first 
  (by creating a new 'double' vector length 4 (nrows of entire table) and  
  assign that; i.e. 'replace' column), or coerce RHS to 'integer' (e.g. 1L,  
  NA_[real|integer]_, as.*, etc) to make your intent clear and for speed.
  Or, set the column type correctly up front when you create the table and 
  stick to it, please.

所以,我想弄清楚如何使用如下语句来诱使 R 重复应用此语句:

for (i in 1:length(LociDT4Length)){
  with(LociDT4Length[[i]], ifelse(Cohort=="RA", V1/62,
                           ifelse(Cohort=="Lupus", V1/62,
                           ifelse(Cohort=="CEU", V1/96, 
                           ifelse(Cohort=="YRI", V1/80,NA)))))
}

或者我想使用 lapply 将此语句应用于此嵌套数组中的 46 个嵌套 DF。

有什么建议吗?如果 ifelse 语法又差又笨重,我也愿意改变它。

非常感谢。

最佳答案

这应该可行:

lapply(LociDT4Length, function(x)
  with(x,ifelse(Cohort %in% c("RA","Lupus"), V1/62,
                ifelse(Cohort=="CEU", V1/96,
                       ifelse(Cohort=="YRI", V1/80,NA)))))

要避免嵌套 ifelse 试试这个:

#define cohort and matching divisor
origin=c("RA","Lupus","CEU","YRI")
divisor=c(62,62,96,80)

#avoid ifelse
lapply(LociDT4Length, function(x)
  with(x,V1/divisor[match(Cohort,origin)]))

关于r - 在 R 中的嵌套数据框中多次调用 ifelse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24115714/

相关文章:

r - 如何在 R 中制作多个 png 文件的多面板图?

r - 转换数字矩阵中snp基因型的数据框

python - 使用 Pandas 的欧几里德距离矩阵

r - 如何在 R 中绘制 3D 条形图

r - 从任意深度的列表中提取值

ios - 从嵌套 NSDictionary 读取值

java - 如何向用户询问一些问题,然后保存答案并重复询问相同的问题

javascript - 嵌套 for 循环增量产生不一致的结果

python - 删除 pandas 数据框中特定字符后的值

html - 如何编写一个 R 函数来创建一系列散布有 markdown 的绘图