用R重新编码变量

Bra*_*sen 24 r

在R中重新编码变量似乎是我最头痛的问题.您使用哪些功能,包,流程来确保最佳结果?

我发现在互联网上很少有一些有用的例子可以为重新编码提供一个通用的解决方案,我很想知道你们和gals正在使用什么.

注意:这可能是社区维基主题.

Ian*_*ows 20

重新编码可能意味着很多事情,并且从根本上说是复杂的.

可以使用以下levels函数更改因子的级别:

> #change the levels of a factor
> levels(veteran$celltype) <- c("s","sc","a","l")
Run Code Online (Sandbox Code Playgroud)

转换连续变量只涉及矢量化函数的应用:

mtcars $ mpg.log < - log(mtcars $ mpg)

对于binning连续数据的查看cutcut2(在hmisc包中).例如:

> #make 4 groups with equal sample sizes
> mtcars[['mpg.tr']] <- cut2(mtcars[['mpg']], g=4)
> #make 4 groups with equal bin width
> mtcars[['mpg.tr2']] <- cut(mtcars[['mpg']],4, include.lowest=TRUE)
Run Code Online (Sandbox Code Playgroud)

对于将连续或因子变量重新编码为分类变量,存在recode于汽车包和recode.variablesDeducer包中

> mtcars[c("mpg.tr2")] <- recode.variables(mtcars[c("mpg")] , "Lo:14 -> 'low';14:24 -> 'mid';else -> 'high';")
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找GUI,Deducer使用Transform和Recode对话框实现重新编码:

http://www.deducer.org/pmwiki/pmwiki.php?n=Main.TransformVariables

http://www.deducer.org/pmwiki/pmwiki.php?n=Main.RecodeVariables

  • 我也喜欢`car`包中的`recode`函数.它还可以用于将一组类别映射到另一组(例如,当您想将一堆小类别折叠为"其他"类别时). (7认同)
  • 当重新编码因子的级别时,我经常使用`dput(levels(var))`,然后粘贴并编辑输出,然后将它赋予`levels(var)< - `.我觉得这很方便. (7认同)

Rom*_*rik 10

我发现mapvaluesplyr包非常方便.包还包含revalue类似的功能car:::recode.

以下示例将"重新编码"

> mapvalues(letters, from = c("r", "o", "m", "a", "n"), to = c("R", "O", "M", "A", "N"))
 [1] "A" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "M" "N" "O" "p" "q" "R" "s" "t" "u" "v" "w" "x" "y" "z"
Run Code Online (Sandbox Code Playgroud)


pet*_*ner 9

当应该转换几个值时,我发现这非常方便(就像在Stata中进行重新编码一样):

# load package and gen some data
require(car)
x <- 1:10

# do the recoding
x
## [1]   1   2   3   4   5   6   7   8   9  10

recode(x,"10=1; 9=2; 1:4=-99")
## [1] -99 -99 -99 -99   5   6   7   8   2   1
Run Code Online (Sandbox Code Playgroud)


Bra*_*sen 5

我发现,在尝试更改它们之前,有时可以更容易地将非数字因子转换为字符.

df <- data.frame(example=letters[1:26]) 
example <- as.character(df$example)
example[example %in% letters[1:20]] <- "a"
example[example %in% letters[21:26]] <- "b"
Run Code Online (Sandbox Code Playgroud)

此外,在导入数据时,在尝试转换之前确保数字实际上是数字可能很有用:

df <- data.frame(example=1:100)
example <- as.numeric(df$example)
example[example < 20] <- 1
example[example >= 20 & example < 80] <- 2
example[example >= 80] <- 3
Run Code Online (Sandbox Code Playgroud)