2013-10-14 56 views
0

創建變量我有三列代表三個重複測量的數據幀:多個條件語句以作爲R

IDPupil 1  2  3 
1  150.5 151.0 150.6  
2  156.3 156.5    
3  145.7 146.0    
4  151.4 151.6    
5  150.0 149.5 150.4  

我想通過三個的計算行平均(或中值)來創建一個新的變量測量基於以下內容:

a)如果col 1和col 2> 0.4之間的差異並且col 3中有值,則計算行中位數。 b)如果col 1和col 2> 0.4之間的差異並且col 3中沒有值,則打印「NULL」 c)在所有其他情況下(即col 1和2之間的差異爲< 0.4)計算行平均值。

我曾嘗試以下:

Hdiff= hwdata$Height1 - hwdata$Height2 
Hdiff2 = abs(Hdiff) 
Hdiff2 

MeanH = if(Hdiff2 > 0.4 && hwdata$Height3 > 0) { 
rowMedians(hwdata[, c("Height1", "Height2", "Height3")], na.rm = TRUE) 

} else if(Hdiff2 > 0.4 & hwdata$Height3 == 0) 
MeanH = "NULL" 

}else rowMeans (hwdata [, c("Height1", "Height2", "Height3")], na.rm = TRUE) 
{ 

我得到的錯誤:

'Error: could not find function "rowMedians"' 

'Error: unexpected '}' in "}"' 

[R =經驗1周。有沒有更簡潔的方式來做到這一點?

+0

你可以用'ifelse'和'申請';您需要提供樣本數據。 – Metrics

+0

提供了好的樣本數據。 – Ash

+0

'}'錯誤是因爲你用括號關閉了第二個'if',但沒有打開它。 –

回答

1

根據您提供的數據,這個工程:

dt<-read.table(text="IDPupil 1  2  3 
1  150.5 151.0 150.6  
2  156.3 156.5 NA   
3  145.7 146.0 NA   
4  151.4 151.6 NA   
5  150.0 149.5 150.4",h=T) 
> ifelse(abs(dt$X1-dt$X2)<0.4,rowMeans(dt[,-1],na.rm=T),apply(dt[,-1],1,median)) 
[1] 150.60 156.40 145.85 151.50 150.00 

如果您科拉姆名Height1等等,那麼你需要改變X1Height1