2015-06-02 25 views
0

我正在處理一個數據幀,其中有一個非常凌亂的兒童年齡數據。有些是幾個月,一些是幾年。我需要一個只有幾個月齡的新專欄。看起來這ifelse結合和轉換混亂的月份/年份數據在R兩列中

G4_R_2_mth G4_R_2_yr 
     18   1 
     NA   16 
     NA   6 
     NA   4 
     0   16 
     0   17 
     0   16 
     5   7 
     0   8 
     0   10 
     0   16 
     11   0 

基本上我想創建一個新的列,說如果「G4_R_2_mth」是一個數字的ifelse,記下這個號碼,但如果「G4_R_2_mth」是NA或0,它給出了值G4_R_2_yr * 12 。

我試過如下:

child$agemonth <- ifelse(child$G4_R_2_mth == '0 | NA', child$G4_R_2_yr*12, child$G4_R_2_mth) 

但得到這個錯誤:

Error in `$<-.data.frame`(`*tmp*`, "agemonth", value = logical(0)) : 
replacement has 0 rows, data has 1102 

也許我的錯誤是簡單,但我欣賞的幫助。一大堆問題之一,讓我瘋狂。

+0

我猜你的問題的一個來源是你的列名稱不匹配。在您的數據中,它表示'月',但在您的代碼中顯示'G4_R_2_mth'。那是故意的嗎? – goodtimeslim

+1

''0 | NA''是一個字符串。 「月」列中沒有這樣的字符串。你需要像'with(child,ifelse(G4_R_2_mth == 0 | is.na(G4_R_2_mth),G4_R_2_yr * 12,G4_R_2_mth))'''。 –

+0

大家好,感謝您的幫助。這些解決方案大多仍然會拋出相同的錯誤,即使在更多地混淆了我的數據之後。可能與我剛剛還不明白的數據集有關。使用@ neerajt的想法如下:''> month <-as.numeric(child $ G4_R_1_2_mth) > year <-as.numeric(child $ G4_R_1_2_yr)* 12 > child $ agemonth < - ifelse ((!is.na(month)&(month> 0)),month,year)' – jlev514

回答

2

這應做到:

child$agemonth <- ifelse((!is.na(child$G4_R_2_mth) & (child$G4_R_2_mth > 0)), 
    child$G4_R_2_mth, 
    child$G4_R_2_yr * 12) 

編輯:良好的通話,清理了,拿出[我]的!

+0

如果我刪除[i]的!謝謝!!! – jlev514

0

'0 | NA'是一個字符串。 「G4_R_2_mth」列中沒有這樣的字符串。你需要這樣的東西:

child$agemonth <- with(child, ifelse(G4_R_2_mth == 0 | is.na(G4_R_2_mth), 
         G4_R_2_yr*12, G4_R_2_mth)) 

child 
# G4_R_2_mth G4_R_2_yr agemonth 
# 1   18   1  18 
# 2   NA  16  192 
# 3   NA   6  72 
# 4   NA   4  48 
# 5   0  16  192 
# 6   0  17  204 
# 7   0  16  192 
# 8   5   7  5 
# 9   0   8  96 
# 10   0  10  120 
# 11   0  16  192 
# 12   11   0  11