2017-08-25 22 views
-2

當沒有其他條件滿足時,我無法獲得for循環來分配字符串'NA'。R:如果我是真的,那麼將字符串分配給矩陣

這是我已經試過......

Height <- c(1.6,3.4,0.42,n/a, 0.5,n/a,1.5,0,n/a,22.0) 
Height <- matrix(Height) 

h_cat <- matrix(, nrow = length(Height), ncol = 1) 
for (i in 1:length(Height)){ 
    if (Height[i]==0) 
    h_cat[i] <- 'NA' 
    if (Height[i]>0 & Height[i]<2) 
    print(Height[i]) 
    h_cat[i] <- '0-2 m' 
    #print(h_cat[i]) 
    if (Height[i]>=2 & Height[i]<5) 
    h_cat[i] <- '2-5 m' 
    if (Height[i]>=5 & Height[i]<10) 
    h_cat[i] <- '5-10 m' 
    if (Height[i]>=10) 
    h_cat[i] <- '>10 m' 
    else 
    h_cat[i] <- 'NA' 
} 

我有is.na(),但沒有運氣去任何一種。

更新

對不起,這是衝。數據添加。

+3

請分享一些數據... https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – snoram

+0

你應該看看'cut'功能 – Dason

+0

'h_cat '是'矩陣',它有行號和列號。它應該被索引爲'h_cat [i,1]'。 –

回答

2

當前代碼有兩個主要問題。

  1. 首先可以通過返回NA的NA == 0來例示。因此,您只能在非NA條目上使用if函數:which(!is.na(Height))
  2. 你的if-else建設的邏輯是不工作,因爲似乎是這樣的意圖。

下面我相信實現自己的意圖:

# Data needs to be numeric to check with ">" 
Height[Height == "n/a", ] <- NA 
Height <- as.numeric(Height) 

h_cat <- matrix(, nrow = length(Height), ncol = 1) 

# Can't have NA in logical tests 
non_na_entries <- which(!is.na(Height)) 
for (i in non_na_entries) { 
    if (Height[i] == 0) { 
    h_cat[i] <- NA 
    } else if (Height[i] > 0 & Height[i] < 2) { 
    h_cat[i] <- '0-2 m' 
    } else if (Height[i] >= 2 & Height[i] < 5) { 
    h_cat[i] <- '2-5 m' 
    } else if (Height[i] >= 5 & Height[i] < 10) { 
    h_cat[i] <- '5-10 m' 
    } else if (Height[i] >= 10) { 
    h_cat[i] <- '>10 m' 
    } else 
    h_cat[i] <- NA 
} 

    h_cat 

    [,1] 
[1,] "0-2 m" 
[2,] "2-5 m" 
[3,] "0-2 m" 
[4,] NA  
[5,] "0-2 m" 
[6,] NA  
[7,] "0-2 m" 
[8,] NA  
[9,] NA  
[10,] ">10 m" 
0

有幾個問題與您的代碼。其中兩人是由snoram解決的。您需要用NA代替'n/a',並且您不需要Height成爲matrix。爲了使代碼完整答案,我將重複NA部分。現在

Height <- c(1.6,3.4,0.42,n/a, 0.5,n/a,1.5,0,n/a,22.0) 
Height[Height == "n/a"] <- NA 

,到複雜的if/else的替代方案是,就像許多人所說的,cut。由於它返回factor類的對象,因此我們需要重新編碼它的返回值。爲此,我將使用包dplyr中的函數。

library(dplyr) 

h_cat <- cut(Height, c(0, 2, 5, 10, Inf)) 
h_cat[Height == 0] <- NA 
h_cat <- recode_factor(h_cat, 
       '(0,2]' = '0-2 m', 
       '(2,5]' = '2-5 m', 
       '(5,10]' = '5-10 m', 
       '(10,Inf]' = '>10 m') 
h_cat <- matrix(as.character(h_cat), ncol = 1) 
h_cat 

我相信這是非常簡單和可讀的。整潔。如果您將來必須回到此代碼中,您可能會發現維護起來更容易。