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:
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])