R coding for selecting subset with criterion "if any of the following condition is true, then select row x"

StackOverflow https://stackoverflow.com/questions/22793866

  •  25-06-2023
  •  | 
  •  

Pergunta

I'm choosing observations to be included in a subset of a larger data set

R code:

var1 <- c(1,0,0,3,1)
var2 <- c(0,0,0,0,0)
var3 <- c(1,1,0,0,0)

df <- cbind(var1, var2, var3)

How could I select the subset of the data that contains only observations having one "1" in any given column (in this case I should end up selecting rows 2 and 5)?

Foi útil?

Solução

Try:

df[rowSums(df==1) == 1,]
     var1 var2 var3
[1,]    0    0    1
[2,]    1    0    0
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top