0

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?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
MariKo
  • 305
  • 4
  • 15

2 Answers2

2

I think I dind´t catch well your question, but if your aim is selecting only MID rows, then you can accomplish with this:

> df[grepl("^MID$", as.character(df$V1)), ]
   V1         V2
2 MID  2.2381472
5 MID -0.6814620
6 MID -0.5936249
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • Seems like `==` should work in this case, or `%in%` for the extension the OP just requested. – Frank Feb 23 '17 at 15:12
2

Don’t use string search here, use comparison:

df[df$V1 == 'MID', ]

This will be a fair bit more efficient, and it’s less code.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214