问题
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