CCA*_*CCA 6 r categories collapse
我确信这是一个非常基本的问题:
在RI中有600,000个分类变量 - 每个变量分类为"0","1"或"2"
我想要做的是折叠"1"和"2"并自己留下"0",这样在重新分类"0"="0"之后; "1"="1"和"2"="1"---最后我只想要"0"和"1"作为每个变量的类别.
另外,如果可能的话,我宁愿不创建600,000个新变量,如果我可以用新值替换现有变量那么好!
最好的方法是什么?
谢谢!
maj*_*nik 12
我发现这更通用了factor(new.levels[x]):
> x <- factor(sample(c("0","1","2"), 10, replace=TRUE))
> x
[1] 0 2 2 2 1 2 2 0 2 1
Levels: 0 1 2
> new.levels<-c(0,1,1)
> x <- factor(new.levels[x])
> x
[1] 0 1 1 1 1 1 1 0 1 1
Levels: 0 1
Run Code Online (Sandbox Code Playgroud)
新的级别向量必须与x中的级别数相同,因此您可以使用字符串和NA执行更复杂的重新编码,例如
x <- factor(c("old", "new", NA)[x])
> x
[1] old <NA> <NA> <NA> new <NA> <NA> old
[9] <NA> new
Levels: new old
Run Code Online (Sandbox Code Playgroud)
Joh*_*ohn 10
recode()对此有点矫枉过正.您的情况取决于它目前的编码方式.假设你的变量是x.
如果是数字
x <- ifelse(x>1, 1, x)
Run Code Online (Sandbox Code Playgroud)
如果它的性格
x <- ifelse(x=='2', '1', x)
Run Code Online (Sandbox Code Playgroud)
如果它是0,1,2级别的因素
levels(x) <- c(0,1,1)
Run Code Online (Sandbox Code Playgroud)
这些中的任何一个都可以跨数据帧dta应用于变量x.例如...
dta$x <- ifelse(dta$x > 1, 1, dta$x)
Run Code Online (Sandbox Code Playgroud)
或者,框架的多个列
df[,c('col1','col2'] <- sapply(df[,c('col1','col2'], FUN = function(x) ifelse(x==0, x, 1))
Run Code Online (Sandbox Code Playgroud)
recode包中有一个函数car(Companion to Applied Regression):
require("car")
recode(x, "c('1','2')='1'; else='0'")
Run Code Online (Sandbox Code Playgroud)
或者对于您在普通 R 中的情况:
> x <- factor(sample(c("0","1","2"), 10, replace=TRUE))
> x
[1] 1 1 1 0 1 0 2 0 1 0
Levels: 0 1 2
> factor(pmin(as.numeric(x), 2), labels=c("0","1"))
[1] 1 1 1 0 1 0 1 0 1 0
Levels: 0 1
Run Code Online (Sandbox Code Playgroud)
更新:要重新编码数据框的所有分类列,tmp您可以使用以下内容
recode_fun <- function(x) factor(pmin(as.numeric(x), 2), labels=c("0","1"))
require("plyr")
catcolwise(recode_fun)(tmp)
Run Code Online (Sandbox Code Playgroud)