dplyr
접근 방식을 사용하여 데이터 프레임의 기존 열을 y
에 다시 코딩하는 새로운 정수 열 recode
을 만드는 방법은 무엇입니까?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을 사용하여 같은 결과를 얻을 수 있습니다. 그러나 열에있는 값을 보거나 명시 적으로 나열하지 않고이 작업을 수행하고 싶습니다.
'dplyr :: recode()'? – RobertMc
'dplyr :: recode()'함수를 사용하여 모든 값을 명시 적으로 언급해야하지 않아야합니까? – Prradep
'forcats' 패키지의'fct_anon'이 유용할까요? – amarchin