我有一个,其中一个列是一个级别具有隐式排序的因素。如何以下列方式将因子级别转换为特定整数:
例如,下面是我的数据框架:
agree <- c("Strongly agree", "Somewhat disagree", "Somewhat agree",
"Neutral", "Strongly agree", "Strongly disagree", "Neutral")
age <- c(41, 35, 29, 42, 31, 22, 58)
df <- data.frame(age, agree)
df
# age agree
# 1 41 Strongly agree
# 2 35 Somewhat disagree
# 3 29 Somewhat agree
# 4 42 Neutral
# 5 31 Strongly agree
# 6 22 Strongly disagree
# 7 58 Neutral
str(df)
# 'data.frame': 7 obs. of 2 variables:
# $ age : num 41 35 29 42 31 22 58
# $ agree: Factor w/ 5 levels "Neutral","Somewhat agree",..: 4 3 2 1 4 5 1现在,我希望使用上面显示的映射将agree列转换为整数列。
我已经搜索了有关将因子转换为整数的其他问题,但它们与维护因子排序无关。
"How to convert a factor to an integer\numeric without a loss of information?“
发布于 2016-07-27 19:21:52
您需要首先定义因素的顺序:
ordering <- c("Strongly disagree", "Somewhat disagree", "Neutral", "Somewhat agree", "Strongly agree")然后,当您第一次创建您的因素时,您应该使用这个定义:
agreeFactor <- factor(agree, levels = ordering)那么,您应该能够得到您的订单因素:
as.numeric(agreeFactor)您也可以在使用as.numeric()时应用顺序,但如果以后决定检索数字向量而忘记应用“level=”参数,则会导致不一致。
e:如果您想直接将数字导入数据,只需使用:
df$agree <- as.numeric(factor(df$agree, levels = ordering))发布于 2019-05-15 20:05:57
如果您的因素已经按级别排序,则可以使用以下函数将该因素转换为数字顺序。
Convert_Numeric = function(X) {
L = levels(X)
Y = as.numeric(factor(X, labels = seq(1:length(L))))
return(Y)
}这对于函数或dplyr尤其有用:
df %>%
mutate(Numeric_version = Convert_Numeric(agree))发布于 2016-07-27 19:29:37
dplyr库对于这种类型的操作有一个有用的revalue函数:
library(plyr)
df$agree<-as.numeric( revalue(df$agree, c("Strongly disagree" = 1,
"Somewhat disagree" = 2,
"Neutral" = 3,
"Somewhat agree" = 4,
"Strongly agree" = 5)) )总的来说,@tluh方法对因素进行排序是一种更好的方法,因为它维护原始输入,并将因素设置为正确的顺序。
https://stackoverflow.com/questions/38621334
复制相似问题