0

I have one expression that I'd like to assign to a variable, because I'll be using it many times throughout a script (mostly in ifelse statements). But right now it's only giving me NA values.

so, for example, I'd like to use something like this:

 x <- df$var1 > 0.5

 df$var2 <- ifelse(x, 1, 0)

that isn't working, and var2 is just a column of NA values. But it currently works if I use:

 df$var2 <- ifelse(df$var1 > 0.5, 1, 0)

I thought it might be due to the quotes generated when you assign the expression to a variable, but this doesn't work either:

 df$var2 <- ifelse(noquote(x), 1, 0)

How do you appropriately assign an expression to a variable?

Geogrammer
  • 137
  • 1
  • 10
  • 2
    R is very much not designed to work like this. It is not a macro language. If you want to dynamically build expressions and evaluate them, you'd have to use things like `eval()` and `substitute()` and `quote()` and `do.call()`. Can't you just store the T/F vector in this case? It would be easiest to help with a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). What do you even expect `x$var2 <- ifelse(x, 1, 0)` to do? Should that be `df$var2 <- ifelse(x, 1, 0)`?? – MrFlick Sep 21 '16 at 04:11
  • Yes, meant 'df$var2 <- ....' – Geogrammer Sep 21 '16 at 04:59
  • What is `x` after `x <- df$var1 > 0.5`? It *should* be a vector of `TRUE`/`FALSE` values, in which case it should work fine in the `ifelse`. – Jonathan Carroll Sep 21 '16 at 05:09
  • Yes, that's working now! :) But I'm getting new errors as I move forward, the ultimate goal is that I would like to create a dataframe or list of these statements that I can iterate through and dynamically create variables. This should be a very simplified reproducible example of what I'm trying to do: `df <- data.frame(a=c(1,2,3,4,5),b=c(0.3,0.2,0.5,0.3,0.7)) conditions <- data.frame(y=df$b>=0.5, z=df$b>=0.7) columns <- c("a","b") for(i in length(columns)){ df[, paste("var_",columns[i],sep="")] <- ifelse(conditions[i],1,0) }` – Geogrammer Sep 21 '16 at 05:24
  • So that I can have new columns in the original dataframe, with binary values representing if they meet certain criteria. It may seem like weird output, but it's requirement of an economic model I'm trying to build (repeat sales model). And I'd like to be able to dynamically create the variables, rather than hard code them, because I'd like to keep things concise and also the criteria may change in the future. – Geogrammer Sep 21 '16 at 05:25
  • 1
    If you have additional issues you'll need to create a new question. I'll vote for this one to close as it seems it was just a typo. – Jonathan Carroll Sep 21 '16 at 05:27

0 Answers0