2016-11-06 62 views
0

我需要創建一個基於列中三個可能值之一的新列。R使用if if邏輯將值賦給新列

這些規則:

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" 

這裏是我的示例代碼

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" 
} 
) 

這是我想對每個基於對myLetters $ letterStatus樣本數據行的數據:

Row 1: third 
Row 2: first 
Row 3: second 

目前我收到「第一個」「第一個」「第一個」,但我不明白爲什麼。

你知道我該如何解決這個問題,爲什麼每一行都得到第一名?

由於使用矢量化(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

感謝,它使用的if else代替ifelse工作就好了,更簡單的比sapply代碼。 – Jazzmine

+0

我有一個後續問題:我如何設置myLetters $ x1的列名? View(myLetters $ x1)中的名稱是它通過像c(3,1,2)那樣解析的值的集合,實際上它是Null,如此命令所示(名稱(myLetters $ letterRating))。如何分配一個實數列名稱呢?我看到這個鏈接http://stackoverflow.com/questions/16030728/how-to-name-the-unnamed-first-column-of-a-data-frame但想分配名稱(即使數據框中有其他列)謝謝 – Jazzmine

+0

在我刷新環境後,它實際上工作正常,謝謝 – Jazzmine