2017-09-04 2 views
0

CSV 파일에 저장된 설문 결과 (범주 형)를 동일한 셀 내에 여러 응답으로했습니다. I는 (가변 수) 나응답을 여러 열로 분할 (숫자로)

for(t in unique(df$response)) 
{df[paste("response",t,sep="")] <- ifelse(df$response==t,1,0)} 

결과는 여기 아래 코드 시도

response <-c(1,2,3,123) 
df <-data.frame(response) 

같이

데이터 보이는 분리 컬럼으로 분할 싶지만 그것이 만들어 내가 데이터를 다음과 같이

012을보고 싶습니다 (123)

head(df) 
response response1 response2 response3 response123 
1  1   1   0   0   0 
2  2   0   1   0   0 
3  3   0   0   1   0 
4  123   0   0   0   1 

새로운 열 3,516,

response response1 response2 response3 
1  1   1   0   0 
2  2   0   1   0 
3  3   0   0   1 
4  123   1   1   1 

것은

+0

'cbind (DF, model.matrix (~ 인자 (응답) -1, DF))'다음를 재설정 할 수있는 여러분의 도움과 조언을 :) 감사합니다 이름. – lmo

답변

1

우리는

df1 <- cbind(df, +(sapply(1:3, grepl, x = df$response))) 
colnames(df1)[-1] <- paste0("response", colnames(df1)[-1]) 
df1 
# response response1 response2 response3 
#1  1   1   0   0 
#2  2   0   1   0 
#3  3   0   0   1 
#4  123   1   1   1 
+0

같은 DF에 포함시킬 방법이 있다면 알려주시겠습니까? 고마워요! – Omar

+0

@Omar 그런 다음 'df'개체, 즉 'df <-cbind (df, + (sapply (1 : 3, grepl, x = df $ response))) – akrun

관련 문제