简体   繁体   中英

Recode several similar variables in R

I am working with a medium size dataset and I am interested in recoding several variables at once.

There are 15 variables coded as factors with three levels. YES=3, NO=2, N/A=1. I would like to recode all 15 variables as numeric. YES=1, NO=0, N/A=NA.

Prior to updating my software, this code worked.

my_data[, 9:23 := lapply(.SD, recode, "'YES'=1;'NO'=0;'N/A'=NA", as.factor.result= FALSE), .SDcols = 9:23] 

Now I am receiving an error "Error: Argument 2 must be named, not unnamed" Please let me know what I am doing wrong/missing here! Thanks in advance!

The following works:

library(dplyr)
library(data.table)

set.seed(10)
sampler <- function() as.character(sample(c(1:3), 20, TRUE))
my_data <- data_frame(
    id = 1:20,
    a = sampler(),
    b = sampler(),
    c = sampler()
)

dt <- data.table(copy(my_data))

recoder <- function(x) {
    x <- as.integer(x) - 2
    x[x < 0] <- NA
    x
}

## data.table approach
cols <- colnames(dt)[-1]
dt[ ,(cols) := lapply(.SD, recoder), .SDcols = cols][]
dt

## dplyr approach
my_data  %>%
    mutate_at(vars(a:c), recoder)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM