如何创建新的整数列recode
,使用y
方法对数据框df
中的现有列dplyr
进行重新编码?
# Generates Random data
df <- data.frame(x = sample(1:100, 50),
y = sample(LETTERS, 50, replace = TRUE),
stringsAsFactors = FALSE)
# Structure of the data
str(df)
# 'data.frame': 50 obs. of 2 variables:
# $ x: int 90 4 33 85 30 19 78 77 7 10 ...
# $ y: chr "N" "B" "P" "W" ...
# Making the character vector as factor variable
df$y <- factor(df$y)
# Structure of the data to llok at the effect of factor creation
str(df)
# 'data.frame': 50 obs. of 2 variables:
# $ x: int 90 4 33 85 30 19 78 77 7 10 ...
# $ y: Factor w/ 23 levels "A","B","C","E",..: 12 2 14 21 12 22 7 1 6 17 ...
# collecting the levels of the factor variable
labs <- levels(df$y)
# Recode the levels to sequential integers
recode <- 1:length(labs)
# Creates the recode dataframe
dfrecode <- data.frame(labs, recode)
# Mapping the recodes to the original data
df$recode <- dfrecode[match(df$y, dfrecode$labs), 'recode']
此代码按预期工作。但我想用dplyr或其他有效方法取代这种方法。如果我知道所有的值,我可以使用this approach来实现相同的目标。但我想在没有看到或明确列出列
中存在的值的情况下这样做答案 0 :(得分:1)
这里的诀窍是,as.numeric(factor)
实际上将整个级别作为整数返回。所以,试试这个
df <- data.frame(x = sample(1:100, 50),
y = sample(LETTERS, 50, replace = TRUE),
stringsAsFactors = FALSE)
library(dplyr)
dfrecode <- df %>%
mutate(recode = as.numeric(factor(y)))
str(dfrecode)