我有一个数据集,在其短暂的版本是这样的:从列查找字符串精确匹配
> df
V1 V2
MID_R 1.243879014
MID 2.238147196
MID_Rcon 0.586581997
MID_U 0.833624164
MID -0.681462038
MID -0.593624936
MID_con 0.060862707
MID_con -0.764524044
MID_R -0.128464132
我写了一个代码只选择MID行和calcualte的手段为他们:
MID_match <- c("MID^") # choosing specific pattern to search through conditions
MID <- df[grepl(paste(MID_match, collapse="|"), df$V1), ] # grouping across this pattern
MID$V2 <- as.numeric(as.character(MID$V2))
mean_MID <- mean(MID$V2) # calculating mean
MID_mean = rbind(MID_mean, data.frame(mean_MID))
,我瞄准的第一和第二行应该是这样的输出:
> MID_match
[1] "MID"
> MID
V1 V2
MID 2.238147196
MID -0.681462038
MID -0.593624936
不过,我让所有组成字符串MID,例如初始数据集的行:
> MID
V1 V2
MID_R 1.243879014
MID 2.238147196
MID_Rcon 0.586581997
MID_U 0.833624164
MID -0.681462038
MID -0.593624936
MID_con 0.060862707
MID_con -0.764524044
MID_R -0.128464132
我尝试使用grep的功能,但它didnt'work:
MID_match <- df$V1(grep("\\bMID\\b", df$V1))
任何想法如何提取确切的MID值?
似乎'=='应该在这种情况下工作,或者'%in%'为OP刚才请求的扩展。 – Frank