Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fast looping through a data frame with an if statement

I have a quite simple but relatively large data frame that looks somewhat like this:

vec1 <- rbinom(350000, 1, 0.1)
vec2 <- rep(NA, length(vec1))
df <- data.frame(vec1, vec2)

I need to assign "not available" or "free" in the second column, depending on if there is a 0 or 1 in the first column of the respective line.

This can be done via loop:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for (i in 1:nrow(df)) {
  if (df[i,1] == 0) {
    data1[i,2] <- "not available"
  } else {
    data1[i,2] <- "free"
  }
}

Unfortunately it takes quite a while this way. I am sure there must be quicker ways to achieve this.
Anybody with a hint?

>Solution :

You can use ifelse

transform(df, vec2 = ifelse(vec1==0, "not available", "free"))

or

transform(df, vec2 = c("free","not available")[(vec1==0)+1])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading