【问题标题】:Is there a way to recode an SPSS function in R to create a single new variable?有没有办法在 R 中重新编码 SPSS 函数以创建一个新变量?
【发布时间】:2019-07-18 13:53:29
【问题描述】:

有人可以帮我将 SPSS 重新编码为 R 吗?

SPSS 代码:

RECODE variable1
(1,2=1)
(3 THRU 8 =2)
(9, 10 =3)
(ELSE = SYSMIS)
INTO variable2

我可以创建具有不同值的新变量。但是,我希望它与 SPSS 一样位于同一个变量中。

非常感谢。

【问题讨论】:

标签: r spss recode


【解决方案1】:
    x <- y<- 1:20
    x
    [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
    y[x %in% (1:2)] <- 1
    y[x %in% (3:8)] <- 2
    y[x %in% (9:10)] <- 3
    y[!(x %in% (1:10))] <- NA
    y
    [1]  1  1  2  2  2  2  2  2  3  3 NA NA NA NA NA NA NA NA NA NA

【讨论】:

    【解决方案2】:

    我写了一个函数,它的编码与 spss 代码重新编码非常相似。看这里

    variable1 <- -1:11
    recodeR(variable1, c(1, 2, 1), c(3:8, 2), c(9, 10, 3), else_do= "missing")
    NA NA  1  1  2  2  2  2  2  2  3  3 NA
    

    此功能现在也适用于其他示例。函数是这样定义的

    recodeR <- function(vec_in, ..., else_do){
    l <- list(...)
    # extract the "from" values
    from_vec <- unlist(lapply(l, function(x) x[1:(length(x)-1)]))
    # extract the "to" values
    to_vec <- unlist(lapply(l, function(x) rep(x[length(x)], length(x)-1)))
    # plyr is required for mapvalues
    require(plyr)
    # recode the variable
    vec_out <- mapvalues(vec_in, from_vec, to_vec)
    # if "missing" is written then all outside the defined range will be missings. 
    # Otherwise values outside the defined range stay the same
    if(else_do == "missing"){
    vec_out <- ifelse(vec_in < min(from_vec, na.rm=T) | vec_in > max(from_vec, na.rm=T), NA, vec_out)
    }
    # return resulting vector
    return(vec_out)}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多