Using ifelse to create a new variable in R, but getting error message unexpected '='

时间:2016-07-11 22:35:37

标签: r if-statement syntax-error

I want to use the values in one of the variables in my dataset to create a new variable which just has zero or one if a given condition in the first variable is true. I tried using ifelse to create this new variable, but no matter what I try, R gives me an error message saying I have an unexpected '=' in my code.

Here is a sample of the data in the variable I'm using to create the second variable:

head(hdd$az_id, n=20)

 [1]  196  196  196  194  194  194  194  194  194  194  195  195 2170
2170  195  195  1576  196  196  194

Here is the ifelse code I tried to write:

hdd$pch <- ifelse(hdd$az_id=1576,1,0)

And the error message:

Error: unexpected '=' in "hdd$pima_hosp<-ifelse(hdd$az_fac_id="

1 个答案:

答案 0 :(得分:4)

It should be == . = is an assignment operator and == is for comparison

hdd$pch <- ifelse(hdd$az_id==1576,1,0)