La Machine Infernale La Machine Infernale - 10 months ago 79
R Question

R: populate a vector incrementally

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:


for (i in 1:length(x)){
ifelse (x[[i]]>0,b<-0.6,b<-0.4)
return (b)

but then


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


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)
#[1] 0.4 0.6 0.6 0.4 0.6