Try to search your question here, if you can't find : Ask Any Question Now ?

How to use ifelse in r with multiple conditions to change another variable to NA

HomeCategory: stackoverflowHow to use ifelse in r with multiple conditions to change another variable to NA
Avatarpushpa asked 4 weeks ago

I have station data with years and rainfall amounts. I am trying to convert specific stations of certain years to missing values (NA) for rainfall. I want everything that is not that specific station/year to keep it’s rainfall amount.

I’ve been using ifelse to specify multiple conditions and designate rainfall as NA. But every time I do this my data frame turns into a value that simply is the number of rows that are not NA.

Here’s some sample data:

STATION<-c(1,1,1,2,2,2)
YEAR<-c(2000,2001,2002,2000,2001,2002)
RAIN<-c(5,4,3,4,3,5)
df<-cbind(STATION,YEAR,RAIN)
df<-as.data.frame(df)

Now, if I want rainfall amounts that are part of station 1 in the year 2001 I am using this ifelse statement:

df<-ifelse(df$STATION==1&&df$YEAR==2001,df$RAIN<-"NA",df$RAIN<-df$RAIN)

With this code, the df becomes a value of 5.

What I want to get is a dataframe that looks like this:

     STATION YEAR   RAIN
[1,] "1"     "2000" "5" 
[2,] "1"     "2001" "NA"
[3,] "1"     "2002" "3" 
[4,] "2"     "2000" "4" 
[5,] "2"     "2001" "3" 
[6,] "2"     "2002" "5"

Anyone know where I am going wrong here?

1 Answers
Best Answer
AvatarArben answered 4 weeks ago
Your Answer

13 + 18 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com