2012-10-31 33 views
0

可能重複:
R if with vectorized statements優化「如果」 R中的數據幀的一行功能

有一些類似的問題如何在這裏最好的矢量化的功能,但我可以」 t找到一個應用if類型函數的示例,按行排列數據框。

給出一個數據幀df,列中包含1912年至2010年的年份值,我只想對某個年份是在測試年份之前還是之後(例如1948年)和在另一列中分配字符「是」或「否」。應該很容易......

目前,我寫的代碼如下:

i = 1 
while (i < nrow(df)) { 
    if (df$Year[i] < 1948) { 
     df$Test[i] <- "Yes"   
    } else { df$Test[i] <- "No" 
    } 
    i = i + 1 
} 

上述作品,但速度很慢大型數據集,我知道必須有一個更「優雅」在R中的解決方案。會更好的方法使用適用?還是有更簡單的東西?

謝謝!

+0

的*另見*節如果「'告訴你看看'ifelse',它就是你想要的。 –

回答

3

你想ifelse(),而不是,它是矢量化和returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE,或者說幫助頁面。

例如:

> years <- 1980:2000 

> ifelse(years < 1986, "old", "young") 
[1] "old" "old" "old" "old" "old" "old" "young" "young" "young" "young" "young" "young" "young" "young" "young" 
[16] "young" "young" "young" "young" "young" "young" 

你甚至可以嵌套ifelse()語句,如果你有2度以上的條件下,與Excel類似的,如果你熟悉=IF()

ifelse(years < 1986, "old", ifelse(years < 1996, "medium", "young")) 
+0

謝謝!這非常有幫助! – jsnider

4

ifelse在這裏更有意義。

df$Test <- ifelse(df$Year < 1948, "Yes", "No") 

ifelse是if/else構造的矢量化版本。使用R時,如果可能的話,使用矢量化解決方案几乎總是更合理。

+0

工程就像一個魅力。謝謝! – jsnider