如何将不同级别的字符串转换为R中的数字响应



首先,我看到了一些类似的问题。我的问题和那些已经解决的问题很相似。但是这细微的差别给我带来了一些问题。

在我的问题中,我有一列数据框架,其中包含五个不同级别的字符串:"10-20%"100+%"21-40%"41-70%"71-100%"。这两个函数我都试过了。数字和整数。这两个函数确实将字符串更改为数字响应。问题是,我想通过遵循数字序列来转换这些字符串。例如,"10-20%"、"100+%"、"21-40%"、"41-70%"、"71-100%",每一个字符串对应的字符串是1,2,3,4,5。

但是我想要的是"10-20%"是1,"21-40%"是2,"41-70%"是3,"71-100%"是4,"100+%"是5。如果我想实现我的目标,我是否必须手动更改这些字符串的级别序列?

附录:

levels(dataset$PercentGrowth)
[1] ""        "10-20%"  "100+%"   "21-40%"  "41-70%"  "71-100%"
head(as.integer(dataset$PercentGrowth))
[1] 1 4 3 1 3 4
head(as.numeric(dataset$PercentGrowth))
[1] 1 4 3 1 3 4
head((dataset$PercentGrowth))
[1]        21-40% 100+%         100+%  21-40%
Levels:  10-20% 100+% 21-40% 41-70% 71-100%

你应该从你的字符串中创建一个因子,按好的顺序分配级别:

x = c("10-20%", "100+%" ,"21-40%" ,"41-70%", "71-100%")
as.integer(factor(x,levels=x))
[1] 1 2 3 4 5
as.numeric(factor(df$string.var, 
    levels = c("10-20%", "21-40%", "41-70%", "71-100%",  "100+%"))
?factor

样本数据会有所帮助。

编辑添加关卡

你可以试试:

x <- c("10-20%", "100+%" ,"21-40%" ,"41-70%", "21-40%", "71-100%", "10-20%")
library(gtools)
match(x,unique(mixedsort(x)))
#[1] 1 5 2 3 2 4 1
##
as.numeric(factor(x, levels=unique(mixedsort(x))))
#[1] 1 5 2 3 2 4 1

假设你的向量是:(非通解)

x1 <- c("less than one year", "one year", "more than one year","one year", "less than one year")

?gsub2()从R:使用gsub替换字符,如何创建一个函数?

gsub2 <- function(pattern, replacement, x, ...) {
for(i in 1:length(pattern))
x <- gsub(pattern[i], replacement[i], x, ...)
x
}
x1[mixedorder(gsub2(c("less","^one","more"), c(0,1,2), x1))]
[1] "less than one year" "less than one year" "one year"          
[4] "one year"           "more than one year"

最新更新