-1

Is there a straightforward way to change the values in column X to NA, based on the value of column Y?

I've got a large dataframe with data for multiple radars. I want to change the column X values (Density) to NA only for radarID "CLX" (column Y).

It Excel this would be a simple select all rows with radarID = "CLX", and replace all Density values with NA.

Thanks

  • Please provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – agstudy Apr 08 '13 at 18:21

3 Answers3

1

One way to do it is as follows. If df is your data frame with two columsn x and y and you want to change x based on y such that when y is less than 10, x should become NA:

df[df$y < 10, 'x'] <- NA

You could also check out ?transform and ?within

ndoogan
  • 1,925
  • 12
  • 15
1

In R also it is too simple, specially if you give us a reproducible example.

Here I create one :

dat <- data.frame( radarID = sample(c("CLX","OTHER"),10,rep=TRUE),
            X = rnorm(10))

Then using transform and ifelse, you can do something like this :

transform(dat,X=ifelse(radarID=='CLX',NA,X))

  radarID           X
1    OTHER -1.03632461
2    OTHER  0.07634564
3    OTHER -0.33788092
4      CLX          NA
5      CLX          NA
6      CLX          NA
7    OTHER  1.37040083
8    OTHER  0.50905176
9      CLX          NA
10   OTHER -0.16086215

Of course this will work in a copy of your data. You need to assign it assign to dat if you want to have the change.

dat <- transform(dat,X=ifelse(radarID=='CLX',NA,X))
agstudy
  • 119,832
  • 17
  • 199
  • 261
0
df = data.frame(Density = 1:4, radarID = c("blah", "boo", "CLX", "bam"))
df$Density[df$radarID == "CLX"] = NA
eddi
  • 49,088
  • 6
  • 104
  • 155