我正在處理一個數據幀,其中有一個非常凌亂的兒童年齡數據。有些是幾個月,一些是幾年。我需要一個只有幾個月齡的新專欄。看起來這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
也許我的錯誤是簡單,但我欣賞的幫助。一大堆問題之一,讓我瘋狂。
我猜你的問題的一個來源是你的列名稱不匹配。在您的數據中,它表示'月',但在您的代碼中顯示'G4_R_2_mth'。那是故意的嗎? – goodtimeslim
''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))'''。 –
大家好,感謝您的幫助。這些解決方案大多仍然會拋出相同的錯誤,即使在更多地混淆了我的數據之後。可能與我剛剛還不明白的數據集有關。使用@ 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