首页 > 解决方案 > 在列名中搜索字符串并检索每一行的相应值

问题描述

我有一个这样的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"

这样做的最佳方法是什么?

标签: rstringdataframesubset

解决方案


我们可以创建一个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

推荐阅读