Function and conditional

2

Good evening. I have two vectors, one with binary data

M <- c(1, 0, 0, 1, 0, 0)

and another with non-binary data C <- c(2.5, 3)

I need to create a function (in R) that assigns a value of vector C, whenever a value of 1 of the vector M is found, that replaces the value of one with the values of C. The example would be:

(2.5, 0, 0, 5.3, 0, 0)

The ideal would be to use if, only I'm not getting to generate that replacement.

    
asked by viviana marquez 26.10.2017 в 00:41
source

2 answers

1

It may be like this:

bin<-c(1,0,0,1,0)
nbin<-c(3.6,4.5)

sustituye_unos<-function(bin,nbin){
     k<-1
     for(i in 1:length(bin)){
          if(bin[i]==1&(!is.na(nbin[k]))){
               bin[i]<-nbin[k]
               k<-k+1
          }else{#¿Que pasa si se terminan los número en nbin?}
     }
     return(bin)
}

> sustituye_unos(bin,nbin)
[1] 3.6 0.0 0.0 4.5 0.0
    
answered by 26.10.2017 в 01:26
1

The easiest and fastest way is this:

m<-c(1,0,0,1,0,0)
c<-c(2.5,3)
m[m == 1] <- c
m
> 2.5 0.0 0.0 3.0 0.0 0.0

But you have to take into account that the values of c are recycled, for example:

m<-c(1,0,0,1,0,0,1,0,1)
c<-c(2.5,3)

m[m == 1] <- c
m

> 2.5 0.0 0.0 3.0 0.0 0.0 2.5 0.0 3.0

If you do not want to recycle the values of c and only replace the n values of c you can do this:

m<-c(1,0,0,1,0,0,1,0,1)
c<-c(2.5,3)
m[which(m == 1)[1:length(c)]]<-c
m

> [1] 2.5 0.0 0.0 3.0 0.0 0.0 1.0 0.0 1.0
    
answered by 26.10.2017 в 05:23