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连续数据的查看cut和cut2(在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
Rom*_*rik 10
我发现mapvalues从plyr包非常方便.包还包含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)
当应该转换几个值时,我发现这非常方便(就像在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)
我发现,在尝试更改它们之前,有时可以更容易地将非数字因子转换为字符.
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)