我想在其他列中基於NAs創建另一列。下面是一個例子:根據其他列中的NA值創建新列
df <- replicate(5,rnorm(4))
df[1,3:4] <- NA
df[2:3,1:2] <- NA
colnames(df)[1:5] <- c("One","Two","Three","Four","Five")
df
One Two Three Four Five
[1,] 0.12 -0.38 NA NA 0.10
[2,] NA NA -0.19 -0.14 -1.57
[3,] NA NA 1.01 0.22 0.27
[4,] 0.53 0.71 -0.86 -0.33 -1.01
每一列具有固定的分配的權重:
weightc1 <- 0.1
weightc2 <- 0.3
weightc3 <- 0.2
weightc4 <- 0.35
weightc5 <- 0.05`
欲讓在NAS中的每一列等於對應的列權重。例如。第1列中的NA爲0.1。
然後,我想創建另一列(稱之爲Six),它等於NA權重的總和。例如,第6列的第一行應該是0.55(0.2 + 0.35)。最後一行,它沒有來港,等於0柱應該是這樣的:
df2 <- cbind(df, Six = c("0.55","0.4","0.4","0"))
df2
One Two Three Four Five Six
[1,] "0.123127305724018" "-0.378163368890999" NA NA "0.100592613978267" "0.55"
[2,] NA NA "-0.190601356688205" "-0.136015883223294" "-1.56573577576604" "0.4"
[3,] NA NA "1.01441506421936" "0.220154629517149" "0.273740027540685" "0.4"
[4,] "0.529632731861426" "0.709285638700681" "-0.864741163519668" "-0.327865814162575" "-1.01298096772074" "0"
我試圖IfesleSix < - ifelse(DF $一個== NA, 「weightc1」, 「」),它用NAs替換第一列中的所有數字。我知道在應用求和函數之前我需要先解決這個問題(或者是否有解決方法?)。請指教。謝謝!
如果創建一個隨機過程的示例(即'rnorm' ..)請使用'set.seed '重現性 –