0

Let's say I have a data.frame like this:

set.seed(42)
data<-data.frame(well = sample(letters[1:4], 40, replace =T),
                measurement_number = rep(1:4, 10),
                values = runif(40))

I'd like to select all the data$values for which data$well =="b" and data$measurement equals values from 1 to 3. Coding that like this: data$values[data$well == "b" & data$measurement_number == c(1:3)] creates a different selection (actually an error in this case). But if I use data$measurement_number == c(1:2) that will select every other 2 values from the column, which is not I want to get. So, far only using OR operator allows me to achieve what I want:

data$values[data$well == "b" & (data$measurement_number == 1|
                               data$measurement_number == 2|
                               data$measurement_number == 3)]

Is there a more direct and concise way to code that I need values from 1 through 3 ?

Thanks a lot! Best regards,

Evgeny

Eugene
  • 85
  • 8
  • 2
    `data$measurement_number %in% 1:3` - asked and answered a lot (but admittedly can be hard to search for). – Ritchie Sacramento May 10 '22 at 22:33
  • 1
    Of course, if you are looking for the rows to select, use which(). In the most recent versions of R that would look like: (data$well == "b" & data$measurement_number %in% 1:3) |> which(). In older versions versions you'd use which(data$well == "b" & data$measurement_number %in% 1:3)) – John Garland May 10 '22 at 22:46

0 Answers0