[英]Ignore NA values in a sample function in R
我試圖忽略采樣 function 中的 NA 值。 這與之前有關在 R 的循環中使用開始和結束值進行采樣的問題有關:在 R 的循環中使用開始和結束值進行采樣。
我使用mapply
找到了解決該問題的方法: df[j,4] <- mapply(function(x, y) sample(seq(x, y), 1), df[j,"start"], df[j,"end"])
。 我已經回到這個問題,但我在處理NA
值時遇到了一些困難。 通常我會嘗試過濾掉start
列和end
列中具有NA
值的行,但循環的其他部分引用將被刪除的行。 我檢查了其他討論使用na.omit
或na.rm
作為可能的解決方案的線程,但正如我所說,過濾掉具有NA
值的行會導致我的代碼中出現其他問題,我認為該sample
沒有na.rm
參數,所以我想看看是否有另一種解決方法。
我使用了與上一個問題相同的數據集,但添加了一些NA
值。我希望得到如下結果:
ID start end sampled
a 25 67 44
b 36 97 67
c 23 85 77
d 15 67 52
e 21 52 41
f NA NA NA
g 39 55 49
h 27 62 35
i 11 99 17
j 21 89 66
k NA NA NA
l 44 58 48
m 16 77 22
n 25 88 65
這是要使用的示例集:
structure(list(ID = c("a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n"), start = c(25, 36, 23, 15, 21,
NA, 39, 27, 11, 21, NA, 44, 16, 25), end = c(67, 97, 85, 67,
52, NA, 55, 62, 99, 89, NA, 58, 77, 88), sampled = c(NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -14L), spec = structure(list(
cols = list(ID = structure(list(), class = c("collector_character",
"collector")), start = structure(list(), class = c("collector_double",
"collector")), end = structure(list(), class = c("collector_double",
"collector")), sampled = structure(list(), class = c("collector_logical",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))
一種簡單的方法是檢查mapply
中的NA
值:
df$sampled <- mapply(function(x, y) if(is.na(x) || is.na(y)) NA else
sample(seq(x, y), 1), df$start, df$end)
或者因為這是使用j
來索引行的較大循環的一部分:
df[j,4] <- mapply(function(x, y) if(is.na(x) || is.na(y)) NA else
sample(seq(x, y), 1), df[j,"start"], df[j,"end"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.