Possible Duplicate:
R if with vectorized statements
there's some similar questions on how to best vectorize functions on here, but I can't yet find an example that applies an if-type function, by row for a data frame.
Give a data frame, df, with column "Year", which holds year values from 1912 - 2010, I simply want to apply a test of whether a given year is before or after a test year (e.g 1948) and assign a character "yes" or "no" in another column. Should be easy...
Currently, I have written the code as follows:
i = 1
while (i < nrow(df)) {
if (df$Year[i] < 1948) {
df$Test[i] <- "Yes"
} else { df$Test[i] <- "No"
}
i = i + 1
}
The above works, but is slow with large datasets, and I know that there must be a more "elegant" solution for this in R. Would a better approach use apply? Or is there something even simpler?
Thanks!