
前回の続き。
下記データフレーム(Dat)で、"Expenses" の値を補完しようと思うけど、

17行目の "Expenses" は、両隣の "Revenue" と "Profit" から計算できる。
この場合は、
"Expenses (経費)" = "Revenue (収益)" - "Profit (利益)"
となる。
これを R で計算するためには、
# Expenses が NA で Revenue と Profit のデータがある行を抽出
Dat[is.na(Dat$Expenses) & !is.na(Dat$Revenue) & !is.na(Dat$Profit),]
目的の行のみを抽出できた。

で、ここの "Expenses" の列の "NA" に "Revenue - Profit" の値を代入したいので、
# Expenses が NA で Revenue と Profit のデータがある行を抽出 し、w に代入
w <- is.na(Dat$Expenses) & !is.na(Dat$Revenue) & !is.na(Dat$Profit)
# 該当のセルに 計算結果を代入
Dat[w,"Expenses"] <- Dat[w,"Revenue"]-Dat[w,"Profit"]
該当の行(17行目)を確認すると、
# 確認
Dat[17,]
無事代入できていた。

リンク
リンク
リンク
リンク