當沒有其他條件滿足時,我無法獲得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(),但沒有運氣去任何一種。
更新
對不起,這是衝。數據添加。
請分享一些數據... https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – snoram
你應該看看'cut'功能 – Dason
'h_cat '是'矩陣',它有行號和列號。它應該被索引爲'h_cat [i,1]'。 –