简体   繁体   English

以“ R”方式将函数应用于两个向量?

[英]Apply a function to two vectors the “R” way?

There are two vectors x and y. 有两个向量x和y。 If x contains an NA I want the NA to be replaced by a value from "y" with the corresponding index. 如果x包含NA ,则希望将NA替换为带有相应索引的“ y”中的值。 Here is some example code that works: 这是一些有效的示例代码:

x <- c(1,2,3,NA,5)
y <- c(6,7,8,9,10)

combineVector <- function(x,y)
{
  for (i in 1:length(x)){
  if (is.na(x[i]) && !is.na(y[i])){
      x[i] = y[i]
    }
  }  
   return (x) 
  }
combineVector(x,y)
# [1] 1 2 3 9 5

I could have written this in almost any programming language. 我本可以用几乎所有编程语言编写的。 Is there a more "R" way to perform this task? 还有执行此任务的“ R”方式吗?

x <- c(1,2,3,NA,5)
y <- c(6,7,8,9,10)

x[is.na(x)] <- y[is.na(x)]

See the above. 见上面。 using is.na() on x returns a logical vector where it is TRUE for the NA elements of x. 在x上使用is.na()返回一个逻辑向量,其中x的NA元素为TRUE。 Using these in the selector for X and Y will select only those NA elements. 在X和Y的选择器中使用这些元素将仅选择那些NA元素。 Using it in assignment will replace the NA elements from x with the corresponding ones from Y. 在分配中使用它会将x中的NA元素替换为Y中的对应元素。

That will be much faster than looping as the vector gets large. 随着向量变大,这将比循环快得多。

Try this code: 试试这个代码:

x[is.na(x)] <- y[is.na(x)]

By subsetting the x vector with is.na(x) you will be assigning only those values of x which are NA to the corresponding indices in the y vector. 由子集划分的x与矢量is.na(x)你将被分配那些的值x ,其是NA在相应的索引y矢量。

To generate a new vector taking x and y as input, you can use the ifelse function: 要生成一个以xy为输入的新向量,可以使用ifelse函数:

x<-c(1,2,3,NA,NA)
y<-c(6,7,8,9,NA)
ifelse(is.na(x), y, x)
# [1]  1  2  3  9 NA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM