忽略R中的样本函数中的NA值

问题描述 投票:0回答:1

我正在尝试忽略采样函数中的NA值。这与先前有关在R中的循环中使用开始和结束值进行采样的问题有关:Sample using start and end values within a loop in R

我使用mapplydf[j,4] <- mapply(function(x, y) sample(seq(x, y), 1), df[j,"start"], df[j,"end"])找到了解决该问题的方法。我已经回到这个问题,但是在处理NA值时遇到一些困难。通常,我只会尝试过滤NAstart列中具有end值的行,但是循环的其他部分引用的是将要删除的行。我已经检查了其他讨论使用na.omitna.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"))
r loops na sample mapply
1个回答
0
投票

一种简单的方法是检查NA中的mapply值:

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"])
© www.soinside.com 2019 - 2024. All rights reserved.