Reputation: 13
I want to create a new column based on a condition from two different columns in the df. I'm using a nested "ifelse":
data_long$benchmark <- ifelse(data_long$axis1<=2 & data_long$axis2<=2, 1,
ifelse(data_long$axis1>=3 & data_long$axis2=2, 2,
ifelse(data_long$axis1=2 & data_long$axis2>=3, 2,
ifelse(data_long$axis1=3 & data_long$axis2=3, 3,
ifelse(data_long$axis1>=4 & data_long$axis2=3, 4,
ifelse(data_long$axis1=3 & data_long$axis2>=4, 4,
ifelse(data_long$axis1>=4 & data_long$axis2=4, 5,
ifelse(data_long$axis1=4 & data_long$axis2>=4, 5,
ifelse(data_long$axis1>=5 & data_long$axis2>=5, 6)))))))))
But I am getting the following error:
Error: unexpected '=' in: "data_long$benchmark <- ifelse(data_long$axis1<=2 & data_long$axis2<=2, "1", ifelse(data_long$axis1>=3 & data_long$axis2="
Upvotes: 0
Views: 1695
Reputation: 1271
The correct symbol for equality in R is ==
Without some sample data, it's not possible to check all of your logic, but the error refers to the fact that you've used =
within your ifelse
statements.
So, for example, where you've used
...
ifelse(data_long$axis1>=3 & data_long$axis2=2, 2,
...
You should be using:
...
ifelse(data_long$axis1>=3 & data_long$axis2 == 2, 2,
...
Also, if you're nesting this many ifelse
statements, I'd recommend looking at the case_when
function in the dplyr
package.
Upvotes: 1