adding new values to a vector based on condition (for and ifelse)

Alexandros Source

I need to create a vector(lets call it "support vector") that matches position in other vector ("main vector") with desired value. My guess is that the easiest way is to use for and ifelse. I am familiar with appending new values to a vector using for but it does not work with ifelse. Here is simple example that shows what I have in mind (please read # description):

#the "main vector" with fixed values
#empty "support vector" which I want fill 
#loop that puts into "support vector" 1 if "ABC" and 0 if "XYZ"
for(i in 1:length(main_vector)){ifelse(main_vector[i]=="ABC",support_vector[i]=1,support_vector[i]=0}

It generates error that suggest = is an issue in my code (or am I wrong?). What method/functions should I use to bypass using =?

Thank you in advance



answered 6 months ago MKR #1

Simplest way could be:

support_vector <- as.numeric(main_vector == "ABC")
> support_vector
#[1] 1 1 1 0

For some reason if OP still want to use for-loop then there is no need of ifelse rather if-else can be more convenient/readable option for argument of length 1.

support_vector <- c()
for(i in 1:length(main_vector)){
      } else {

Note: Solution provided by @gdkrmr is very elegant.

answered 6 months ago mysteRious #2

Here's another approach (not as nice as @gdkm or @MKR but may be useful in some way):

> main_vector=c("ABC","ABC","ABC","XYZ")
> support_vector <- sapply(main_vector, function(x) as.integer(x=="ABC"))
> support_vector
  1   1   1   0 

comments powered by Disqus