Function recode (car package) - recode argument and equal sign

I would like to know if equals ( =) is allowed to be used in recodesfunction parameter recodein car package?

For example, the following is done:

library(car)
n <- c(0, 10, 20, 21, 60, 70)
r <- recode(n, " 0:20 = '<= 20' ; 20:70 = '> 20' ")
# Error in recode(n, " 0:20 = '<= 20' ; 20:70 = '> 20' ") : 
# in recode term:  0:20 = '<= 20' 
# message: Error in parse(text = strsplit(term, "=")[[1]][2]) : 
#  <text>:1:2: unexpected INCOMPLETE_STRING
# 1:  '<
# ^

Removing =from <= 20works fine:

r <- recode(n, " 0:20 = '< 20' ; 20:70 = '> 20' ")
table(r) 
r
# < 20 > 20 
# 3    3 

Given what I use recodein a context where I accept the argument recodesas user input, I hope that any solution does not require explicit escape characters, as that would be burdensome.

I am launching R version 3.2.3 (2015-12-10) - "Wooden Christmas tree"

+4
source share
3 answers

car::recode , recode ( , "" ).

cut :

n <- c(0, 10, 20, 21, 60, 70)
cut(n,breaks=c(-1,20,Inf),labels=c("<= 20", ">20"))

plyr::revalue (. plyr::mapvalues):

x <- factor(c("a","b","c"))
revalue(x,c("a"=">= 20"))

"-":

x <- factor(letters[1:8])
oldvals <- list(c("a","b","c"),c("d","e"),c("f","g","h"))
newvals <- c("new1","new2","new3")
for (i in seq_along(oldvals)) {
    m <- which(levels(x) %in% oldvals[[i]])
    if (length(m)>0) 
       levels(x)[m] <- rep(newvals[i],length(m))
}

, / - ...

+2

, recode , recodes

, , :

map_em = function(
  n, 
  recs = readline(prompt = "enter map like key = value, key2 = value2: \n")
){
    m = eval(parse(text = sprintf("list(%s)", recs)))
    s = stack(m)
    s$ind[ match(n, s$value) ]
}

# usage example
map_em(n)
# enter map like key = value, key2 = value2: 
'<= 20' = 0:20, '> 20' = 21:70
# [1] <= 20 <= 20 <= 20 > 20  > 20  > 20 
# Levels: <= 20 > 20

match, (, OP, 0:20 20:70), .


, :

map_em2 = function(n, ...){
    m = list(...)
    s = stack(m)
    s$ind[ match(n, s$value) ]
}

# usage example    
map_em2(n, '<= 20' = 0:20, '> 20' = 21:70)
# [1] <= 20 <= 20 <= 20 > 20  > 20  > 20 
# Levels: <= 20 > 20
+2

I had the same problem and could not find any solution. Here is my awkward solutions usinggsub

r <- recode(n, " 0:20 = '< 20' ; 20:70 = '> 20' ")
r <- gsub("< 20", "<= 20", r)
+1
source

All Articles