duckduckgoes duckduckgoes - 17 days ago 5
R Question

Code a new variable for a dataset using multiple logical operators in R

I am trying to convert SAS script to R to learn R. Below is the script in SAS.

if continent=1 and (country=5 or country=10) then rate = 8


Here are my attempts for the dataframe called data:

data$rate[(continent==1) & (country==5 | country==10)] <- 8


Or:

data$rate[(continent==1) & country %in% c(5,10)] <-8


Unfortunately, the attempts do not generate the result correctly. The result shows the rate 8 when either continent=1 or country=5 or country=10. I guess I am wrong on combining logical operators in R.

Could anyone help me fix the issue? Many thanks!

Note: I used attach(data) above since I am lazy to rewrite data again.

Answer

It looks like your issue is that you did not call the variable from the data from the dataframe data. This may be the cause of your error. To fix this, specify the variable within the dataframe by doing:

data$rate[(data$continent==1 & (data$country==5 | data$country==10))] <- 8

Comments