Yoav Eilon
Yoav Eilon

Reputation: 27

Simple recoding in R

Im trying to recode multiple values in a column, it should be very simple. recode the values -9,-8,-7 to NA in variable "var" the stata equivalent is recode var_name (-9=.)(-8=.)(-7=.)(-2=.)(-1=.)

Thanks

Upvotes: 0

Views: 115

Answers (3)

neilfws
neilfws

Reputation: 33802

Assuming you have a data frame, mydata, with the values in column var, you could use ifelse() to generate the new values. Here they are stored in column y but you could alter column var if desired.

mydata$y <- ifelse(mydata$var %in% c(-9, -8, -7, -2, -1), NA, mydata$var)

Upvotes: 1

Sirius
Sirius

Reputation: 5429

your.data$var[ your.data$var %in% c( -9, -8, -7,-2,-1 ) ] <- NA

Find the ones matching your numbers and insert NA there

Upvotes: 1

arunppsg
arunppsg

Reputation: 1563

You can use the library naniar for that.

> df <- data.frame(col1=c(-9, -8, 2, 4))
> df <- replace_with_na(df, replace=list(col1=c(-9, -8)))
> print (df$col1)
[1] NA NA  2  4

Reference on naniar here.

Upvotes: 1

Related Questions