La Machine Infernale - 1 year ago 93

R Question

I'm trying to write a short function that assigns values and populates incrementally a vector, based on values in another vector.

For instance, if I have a vector of binaries a = [0,1,1,0,1], I want to create a vector b of the same length as a, that assigns a value x if a[1]=0, or a value y if a[1]=1. So b = [0.4,0.6,0.6,0.4,0.6]

I have done this:

`a<-sample(0:1,20,replace=T)`

assign<-function(x){

c<-vector()

for (i in 1:length(x)){

ifelse (x[[i]]>0,b<-0.6,b<-0.4)

c[[length(c)+1]]=b}

return (b)

}

but then

`assign(a)`

only returns the first assignment. I assume I didn't nest the loop correctly?

Answer Source

As you state that your vector `a`

is binary, you can turn it into a vector of indices and use that "property":

```
bfroma <- function(x) c(0.4, 0.6)[x+1]
a <- c(0, 1, 1, 0, 1)
bfroma(a)
#[1] 0.4 0.6 0.6 0.4 0.6
```