-1

Take a data frame like mtcars (but much bigger)

I would like to get a list of observations where the value of vs==1 and the value of am != 1. I don't want to have to scroll through a long list of 1s and zeros, but actually get a list of the observations. I could write a loop but is there a more R'ish way of answering that question?

Additional information

My actual example is looking for values in first which are NA while in Grade they are not NA. And this does not seem to work. Does NA get treated special?

x = subset(spreadgrades, first == NA & Grade == NA)
pitosalas
  • 10,286
  • 12
  • 72
  • 120

2 Answers2

2

Using data.table:

library(data.table)
mtcars<-data.table(mtcars)
mtcars[(vs==1 & am!=1),]

     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
1: 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
2: 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
3: 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
4: 22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
5: 19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
6: 17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
7: 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1
amonk
  • 1,769
  • 2
  • 18
  • 27
  • Notice that `data.table` is unnecessary here. Within a `data.frame` you can also do `mtcars[(mtcars$vs==1 & mtcars$am!=1),]` – Jesús Ros Jun 07 '17 at 15:00
  • @gunbl4d3 I ain't using the "$" inside the syntax.. – amonk Jun 07 '17 at 15:01
  • 2
    You should probably use an example containing NA in the `==` col just to confirm it does what OP wants. I have run into related issues before https://stackoverflow.com/questions/16221742/subsetting-a-data-table-using-some-non-na-excludes-na-too Oh, never mind, OP chose to talk about two different examples for some reason. – Frank Jun 07 '17 at 15:04
  • @Frank exaclty :) ! – amonk Jun 07 '17 at 15:05
1

Based on comments and answers, I settled on this:

subset(spreadgrades, is.na(first) & !is.na(Grade))
pitosalas
  • 10,286
  • 12
  • 72
  • 120
  • 1
    Good that you found an answer, but not cool to change your example after an answer is posted. Also, obviously you should post a reproducible example in the question, not just a single line of code... – Frank Jun 07 '17 at 15:06
  • yeah I know. I was trying to make it reproducible by using a well known data frame, but I didn't realize until the first answer, that NA was a key part of the problem that I was having. – pitosalas Jun 07 '17 at 15:10