recode and target of assignment expands to non-language object [duplicate]

血红的双手。 提交于 2019-12-11 20:29:15

问题


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.


回答1:


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 "--->".



来源:https://stackoverflow.com/questions/20549093/recode-and-target-of-assignment-expands-to-non-language-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!