I have a dataset that in its short version looks like this:
> 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
I have written a code to select only MID rows and calcualte the means for them:
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))
The output of the first and second lines that I am aiming for should look like this:
> MID_match
[1] "MID"
> MID
V1 V2
MID 2.238147196
MID -0.681462038
MID -0.593624936
However, I am getting all the rows that comprise the string MID, e.g., the initial dataset:
> 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
I tried using grep function but it didnt'work:
MID_match <- df$V1(grep("\\bMID\\b", df$V1))
Any ideas on how to excract the exact MID value?