r - 在列名中搜索字符串并检索每一行的相应值
问题描述
我有一个这样的df:
id <- c("defoo","ghfoo","abfoo")
abc <- c(.3,.1,.4)
ghi <- c(.4,.2,.2)
abc_dif <- c(.4,.3,.8)
def_dif <- c(.5,.7,.6)
ghi_dif <- c(.2,.1,.9)
df <- data.frame(id,abc,ghi,abc_dif,def_dif,ghi_dif)
我想查找名称包含 id 行中值的前两个字符并且还包含“dif”的列,并为每一行创建一个包含这些列中相应值的新列。
在此示例数据中,新列将是
df$result <- c(.5,.1,.8)
我的无数次尝试都涉及到各种版本的 sapply 和 apply,比如下面的尝试简单地获取列索引:
df$result <- apply(substr(df[,which(colnames(df)=="id")],1,2),1,function(x) grep(x,colnames(df[which(grepl("dif",colnames(df),fixed=TRUE))]),fixed = TRUE))
这给出了错误:
"Error in apply(substr(df[, which(colnames(df) == "id")], 1, 2), 1, function(x) grep(x, : dim(X) must have a positive length"
这样做的最佳方法是什么?
解决方案
我们可以创建一个row/column
索引来获取值
df$result <- df[4:6][cbind(1:nrow(df), match( substr(df$id, 1, 2),
substr(names(df)[4:6], 1, 2)))]
df$result
#[1] 0.5 0.1 0.8
推荐阅读
- python - 如何从同步和异步方法运行 asyncio 方法?
- highcharts - Highcharts - 工具提示渲染性能下降
- javascript - jsPDF围绕自己的中心旋转图像
- objective-c - 为什么发布版本比调试更严格
- java - 局部变量未初始化
- amazon-cloudformation - Terraform 资源弹性负载均衡器 - 减少 ConnectionDrainingPolicy 超时
- excel - 优秀团队出勤率
- html - 同步融合时间表角度组件的动态视图
- vue.js - 进行简单的重新分配后数据属性不再反应?
- javascript - jQuery上一个按钮没有按预期工作