Matthias Zerban
Matthias Zerban

Reputation: 1

Using multiple logical criteria for subsetting in r

I have a dataset (loadings from an efa) with three variables/factors (ML1, ML2, ML3) and I would like to extract the names of cases that have an absolute value of >= 0.3 for exactly one variable/factor.

This is what I worked out so far:

items <- row.names(loadings1[(abs(loadings1$ML1) >= 0.3 | abs(loadings1$ML2) >= 0.3 | abs(loadings1$ML3) >= 0.3) & sum(abs(loadings1$ML1) >= 0.3 , abs(loadings1$ML2) >= 0.3 , abs(loadings1$ML3) >= 0.3 ) == 1,])

It only returns an empty character and I know that it is not because there are no cases that match my criteria.

I also tried:

row.names(loadings1[abs(loadings1$ML1) >= 0.3 | abs(loadings1$ML2) >= 0.3 | abs(loadings1$ML3) >= 0.3 & sum(abs(loadings1$ML1) >= 0.3 , abs(loadings1$ML2) >= 0.3 , abs(loadings1$ML3) >= 0.3 ) == 1,])

The second attempt seemed to ignore the & condition entirely even though the different or conditions worked.

I also found this for help and didn't really see why it wouldn't work in my case.

Any ideas?

Upvotes: 0

Views: 59

Answers (2)

GKi
GKi

Reputation: 39707

You can use rowSums to find rows where exactly one variable is >= 0.3.

items <- row.names(loadings1)[rowSums(abs(loadings1[c("ML1","ML2","ML3")]) >= 0.3) == 1]
items
#[1] "6" "7"

Data:

set.seed(1)
(loadings1 <- data.frame(id = 1:10, ML1 = rnorm(10), ML2 = rnorm(10), ML3 = rnorm(10)))
#   id        ML1         ML2         ML3
#1   1 -0.6264538  1.51178117  0.91897737
#2   2  0.1836433  0.38984324  0.78213630
#3   3 -0.8356286 -0.62124058  0.07456498
#4   4  1.5952808 -2.21469989 -1.98935170
#5   5  0.3295078  1.12493092  0.61982575
#6   6 -0.8204684 -0.04493361 -0.05612874
#7   7  0.4874291 -0.01619026 -0.15579551
#8   8  0.7383247  0.94383621 -1.47075238
#9   9  0.5757814  0.82122120 -0.47815006
#10 10 -0.3053884  0.59390132  0.41794156

Upvotes: 2

Adam
Adam

Reputation: 83

Using a dplyr method, you can do it this way. case_when is useful when applying multiple conditions.

set.seed(1)
df <- tibble(id = 1:10, ML1 = rnorm(10), ML2 = rnorm(10), ML3 = rnorm(10))
df %>% 
  mutate(
    Which = case_when(
      abs(ML1) >= 0.3 & abs(ML2) < 0.3 & abs(ML3) < 0.3 ~ "ML1",
      abs(ML2) >= 0.3 & abs(ML1) < 0.3 & abs(ML3) < 0.3 ~ "ML2",
      abs(ML3) >= 0.3 & abs(ML1) < 0.3 & abs(ML2) < 0.3 ~ "ML3",
    )
  ) %>%
  filter(!is.na(Which)) %>%
  select(id) %>%
  unlist

This prints a list of the ids which qualify. You could also leave it as a data frame and get more information, such as which ML column was >= 0.3.

Edit: Forgot absolute value. Also, Using your method would work, but you have to use parentheses around each condition such as (cond1 & !cond2 & !cond3) | (!cond1 & cond2 & !cond3).

Upvotes: 1

Related Questions