将函数应用于R中的字符框架

Apply function to frame of characters in R

我有一组变量,它们是我试图通过创建以下函数并使用 apply() 函数将其转换为二进制的字符:

a <- as.factor(c("n/a", "False", "False", "True"))
b <- as.factor(c("n/a", "True", "False", "True"))
y <- data.frame(a,b)


conv <- function(x){
    levels(x)[which(levels(x)=="n/a")] <- NA
    levels(x)[which(levels(x)=="False")] <- 0
    levels(x)[which(levels(x)=="True")] <- 1
    x <- as.numeric(levels(x))[x]
    return(x)
}

apply(y,2, conv)

但是,当我这样做时,它会输出 NA。或者,如果您按列应用该函数,它会起作用:

conv(y[,1])
conv(y[,2])

预期的输出应该是:

y:
NA NA
0 1
0 0 
1 1

有没有想过为什么会这样?谢谢

R 中,逻辑值为 TRUE/FALSE 而不是字符串 "True"、"False"。另外,NA是缺失值

y[] <- NA^(is.na(replace(as.matrix(y), y=="n/a", NA)))*+(y=='True')
y
#   a  b
#1 NA NA
#2  0  1
#3  0  0
#4  1  1

你的功能很好你只需要使用lapply

conv <- function(x){
    levels(x)[which(levels(x)=="n/a")] <- NA
    levels(x)[which(levels(x)=="False")] <- 0
    levels(x)[which(levels(x)=="True")] <- 1
    x <- as.numeric(levels(x))[x]
    return(x)
}

lapply(y,conv)

此外,如果所有变量的级别顺序都相同,那么您可以这样做。

conv <- function(x){
    levels(x)=c(0,NA,1)
    return(x)
}

lapply(y, conv)

一个简单的 ifelse 就可以满足 NA 的要求。 grepl 然后可以用来转换为 0/1,即

y[] <- lapply(y[], function(i) ifelse(i == 'n/a', NA, grepl('True', i)*1))
y
#   a  b
#1 NA NA
#2  0  1
#3  0  0
#4  1  1