0

I am trying to recode a variable.

library(car)

There is no problem for

 bd2011$diag = recode(bd2011$value, 
                 "'7400' <- 'dia1'; else = 'b'")

But for

bd2011$diag = recode(bd2011$value,
                 " c('7400','7401') <- 'dia1'; else = 'b'")  

will generate

 Error in c("7400", "7401") <- "dia1" : 
  target of assignment expands to non-language object

What is the problem? How to correct? Thanks.

user1582755
  • 213
  • 1
  • 2
  • 9

1 Answers1

2

You should not be single quoting the LHS expressions (unless they are character values) and you should not be using "<-". The value pairs are supposed to be delivered as:

c(7,8,9)='high'

You might have gotten away with it for a single vector to single item assignment, but with this you are trying to make an assignment from one item to two character values:

c('7400','7401') <- 'dia1'

The recode function is actually making the assignment in the other direction, so using "<-" is really confusing as well as incorrect syntax.

You can see why problems will develop by looking at the code that loops over the "recode.list":

for (term in recode.list) {
    if (0 < length(grep(":", term))) {...}
    else if (0 < length(grep("^else=", squeezeBlanks(term)))) { ...}
    else {...}

Notice: no consideration of the possibility that someone would use "<-" or "->".

Then this is what is in the last else-consequent (which would ignore the "<-"):

        set <- eval(parse(text = strsplit(term, "=")[[1]][1]))
        target <- eval(parse(text = strsplit(term, "=")[[1]][2]))
        for (val in set) {
            if (is.na(val)) 
              result[is.na(var)] <- target
            else result[var == val] <- target

So it should be easy to see that the LHS is being evaluated and assigned to the "target" which comes from the RHS. So if there were a direction to use for assignment, it would have been "--->".

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Thanks. I took off the quote and there is no error. But the value is chr. > str(bd2011) 'data.frame': 1523420 obs. of 6 variables: $ data.yr : chr "2011" "2011" "2011" "2011" ... $ hospital.id : chr "0622" "0622" "0622" "0622" ... $ patient.ctrl.num : chr "1564036" "1564127" "1564182" "1564215" ... $ medical.health.rec.num: chr "007054047" "007054055" "007054059" "007054061" ... $ variable : Factor w/ 19 levels "diagnosis1","diagnosis2",..: 1 1 1 1 1 1 1 1 1 1 ... $ value : chr "V3000" "V3000" "V3000" "V3000" ... – user1582755 Dec 12 '13 at 20:06
  • That comment is pretty useless. Please delete it and edit your Q to have formatted material that makes a reproducible example. – IRTFM Dec 12 '13 at 20:29