2016-11-06 3 views
0

컬럼에있는 세 가지 가능한 값 중 하나를 기반으로 새로운 컬럼을 작성해야합니다.R 다른 컬럼을 사용하여 새 컬럼에 값을 할당하십시오.

If it has c somewhere in it, the new column should be assigned "third" 
If it has b, but not c somewhere in it, the new column should be assigned "second" 
If it has a but not b or c somewhere in it, the new column should be assigned "first" 

여기 이것은 내가 myLetters $ letterStatus에 대한 샘플 데이터를 기반으로 각 행에 대해 원하는 데이터를 내 샘플 코드

x <- c('a,b,c', 'a', 'a,b') 

myLetters <- data.frame(x) 

setnames(myLetters, "theLetter") 

sapply(myLetters$, theLetter, function(x) 
if ('c' %in% myLetters$theLetter) { 
    myLetters$letterStatus <- "third" 
} else if ('b' %in% myLetters$theLetter) { 
    myLetters$letterStatus <- "second" 
} else if ('a' %in% myLetters$theLetter) { 
    myLetters$letterStatus <- "first" 
} 
) 

입니다 :

은 규칙입니다
Row 1: third 
Row 2: first 
Row 3: second 

현재 "첫 번째" "첫 번째" "첫 번째"가 표시되지만 이유를 이해할 수 없습니다.

내가 이것을 해결할 수있는 이유와 왜 각 행에 대해 첫 번째 이유가 있는지 알고 계십니까?

감사 결과를 얻기 위해 vectorisation (우리에게 R의 선물)를 사용하여

답변

0

는 :

x <- c('a,b,c', 'a', 'a,b') 
myLetters <- data.frame(x) 
# myLetters 
# x 
# 1 a,b,c 
# 2  a 
# 3 a,b 

myLetters$x1 = ifelse(grepl("c",myLetters$x), "third", ifelse(grepl("b",myLetters$x),"second", "first")) 
+0

감사합니다,이 경우 대신 다른 ifelse의 사용 sapply 코드보다 잘 간단했다. – Jazzmine

+0

나는 다음과 같은 질문을 가지고있다 : myLetters $ x1의 컬럼 이름을 어떻게 설정 하는가? View (myLetters $ x1)의 이름은 c (3, 1, 2)와 같이 구문 분석 한 값의 집합이며 실제로이 명령 (names (myLetters $ letterRating))과 같이 Null입니다. 열 이름에? 나는이 링크를 참조하십시오 http://stackoverflow.com/questions/16030728/how-to-name-the-unnamed-first-column-of-a-data-frame하지만 그냥 이름을 할당하고 싶습니다 감사합니다 – Jazzmine

+0

감사합니다 – Jazzmine