将 NA 重新插入向量 [英] Re-inserting NAs into a vector
问题描述
我有一个包含 NA 的值向量.这些值需要由无法处理 NAs 的外部程序处理,因此它们被剥离,写入文件,处理,然后读回,从而产生一个长度为非 NAs 数量的向量.例如,假设输入是 7 3 4 NA 5 4 6 NA 1 NA,那么输出就是 7 个值.我需要做的是将 NA 重新插入到位.
I have a vector of values which include NAs. The values need to be processed by an external program that can't handle NAs, so they are stripped out, its written to a file, processed, then read back in, resulting in a vector of the length of the number of non-NAs. Example, suppose the input is 7 3 4 NA 5 4 6 NA 1 NA, then the output would just be 7 values. What I need to do is re-insert the NAs in position.
所以,给定两个向量 X 和 Y:
So, given two vectors X and Y:
> X
[1] 64 1 9 100 16 NA 25 NA 4 49 36 NA 81
> Y
[1] 8 1 3 10 4 5 2 7 6 9
生产:
8 1 3 10 4 NA 5 NA 2 7 6 NA 9
(你可能注意到 X 是 Y^2,这只是一个例子).
(you may notice that X is Y^2, thats just for an example).
我可以敲出一个函数来做到这一点,但我想知道是否有任何巧妙的方法可以做到这一点......拆分,列表,长度......嗯......
I could knock out a function to do this but I wonder if there's any nice tricksy ways of doing it... split, list, length... hmmm...
推荐答案
同一主题的另一个变体
rena <- function(X,Z){
X[which(!is.na(X))]=Z
X
}
R 自动用 NA 填充其余部分.
R automatically fills the rest with NA.
Marek 更正.
这篇关于将 NA 重新插入向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!