2017-11-02 9 views
1

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을 사용하여 같은 결과를 얻을 수 있습니다. 그러나 열에있는 값을 보거나 명시 적으로 나열하지 않고이 작업을 수행하고 싶습니다.

+0

'dplyr :: recode()'? – RobertMc

+0

'dplyr :: recode()'함수를 사용하여 모든 값을 명시 적으로 언급해야하지 않아야합니까? – Prradep

+1

'forcats' 패키지의'fct_anon'이 유용할까요? – amarchin

답변

0

여기에있는 속임수는 실제로 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) 
+1

'df $ y <- factor (df $ y)'를 파이프에 포함시킬 수 있습니까? 이것은 내가 해결하지 못한 주요한 장애물이었습니다. – Prradep

+0

나는 그것을 포함 할 필요가 없다고 생각한다. 그냥 factor (y)를 돌연변이시킬 수있다. 나는 내 대답을 편집했다. – ANG

+0

@Pradep, 작동합니까? – ANG