Using multiple criteria in subset function and logical operators

后端 未结 2 1190
遥遥无期
遥遥无期 2020-11-28 09:56

If I want to select a subset of data in R, I can use the subset function. I wanted to base an analysis on data that that was matching one of a few criteria, e.g. that a cert

2条回答
  •  迷失自我
    2020-11-28 10:28

    For your example, I believe the following should work:

    myNewDataFrame <- subset(bigfive, subset = bf11 == 1 | bf11 == 2 | bf11 == 3)
    

    See the examples in ?subset for more. Just to demonstrate, a more complicated logical subset would be:

    data(airquality)
    dat <- subset(airquality, subset = (Temp > 80 & Month > 5) | Ozone < 40)
    

    And as Chase points out, %in% would be more efficient in your example:

    myNewDataFrame <- subset(bigfive, subset = bf11 %in% c(1, 2, 3))
    

    As Chase also points out, make sure you understand the difference between | and ||. To see help pages for operators, use ?'||', where the operator is quoted.

提交回复
热议问题