【问题标题】:recode (car package) function - recodes argument and equals sign重新编码(汽车包)功能 - 重新编码参数和等号
【发布时间】:2016-07-24 00:50:47
【问题描述】:

我想知道car包中recode函数的recodes参数是否允许使用等号(=)?

例如,以下失败:

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:  '<
# ^

&lt;= 20 中删除= 可以正常工作:

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

鉴于我在将recodes 参数作为用户输入的上下文中使用recode,我希望任何解决方案都不需要显式转义字符,因为这会很麻烦。

我正在运行 R 版本 3.2.3 (2015-12-10) -- “木制圣诞树”

【问题讨论】:

  • 为什么不稍后替换它呢? r &lt;- gsub( "~", "=", recode(n, " 0:20 = '&lt;~ 20' ; 20:70 = '&gt; 20' ") )
  • 这和@Jianfeng 下面的回答很相似……

标签: r r-car recode


【解决方案1】:

我遇到了同样的问题,但没有找到任何解决方案。 这是我笨拙的解决方案,使用gsub

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

【讨论】:

    【解决方案2】:

    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))
    }
    

    如果新/旧代码以某种病态方式重叠,这可能会有点难看...

    【讨论】:

      【解决方案3】:

      鉴于我在将recodes 参数作为用户输入的上下文中使用recode

      我不确定这意味着什么,但这对最终用户来说是相当友好的:

      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:2020: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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 1970-01-01
        • 2023-03-24
        • 2019-10-31
        • 1970-01-01
        相关资源
        最近更新 更多