级与在r个元素

问题描述:

我有不同元素的两个向量,比方说x=c(1,3,4)的识别,y= c(2,9)级与在r个元素

我想范围的矢量识别我矢量x与1和元素的那些y与0,即

(1,2,3,4,9)----->(1,0,1,1,0)

你怎么能得到的零和一的矢量(1,0 ,1,1,0)in r?

感谢

+0

这似乎是题外话,因为它主要涉及有R编程。 –

必须首先定义一个这样做的功能

blah <- function(vector, 
       x=c(1,3,4), 
       y= c(2,9)){ 
outVector <- rep(x = NA, times = length(vector)) 
outVector[vector %in% x] <- 1 
outVector[vector %in% y] <- 0 
return(outVector) 
} 

那么你可以使用的功能:

blah(vector = 1:9) 
blah(vector = c(1,2,3,4,9)) 

你也可以改变X &的y值

blah(vector = 1:10,x = c(1:5*2), y = c((1:5*2)-1)) 

以下选项肯定不是数字上最佳的,但它是最简单直接的方法:

a<-c(1,2,3,4) 
b<-c(5,6,7,8) 
f<-function(vec0,vec1,inp) 
{ 
    out<-rep(NA,length(inp))  #NA if input elements in neither vector 

    for(i in 1:length(inp)) 
    {          #Logical values coerced to 0 and 1 at first, then 
    if(sum(inp[i]==vec0))(out[i]<-0); #summed up and if sum != 0 coerced to logical "TRUE" 
    } 

    for(i in 1:length(inp)) 
    { 
    if(sum(inp[i]==vec1))(out[i]<-1); 
    } 

    return (out) 
} 

工作得很好:

> f(vec0=a,vec1=b,inp=c(1,6,4,8,2,4,8,7,10)) 
[1] 0 1 0 1 0 0 1 1 NA