Ramon
Ramon

Reputation: 3

Create vector using for loop with if else condition

How can I turn the 3 item output of the for loop below into a data frame. In attempting a solution, I've tried:

-Creating an object related to the for loop, but couldn't succeed -Creating a matrix, to no effect

What code would turn the output into a vector or list?

> for(i in X$Planned)ifelse(is.na(i),print("ISNA"),print("NOTNA"))
[1] "NOTNA"
[1] "NOTNA"
[1] "ISNA"

Upvotes: 0

Views: 51

Answers (1)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9865

sapply(x$Planned, function(elem) if (is.na(elem)) {"isNA"} else {"notNA"})

# this will do it!

# however, it will be slower than the vectorized form

ifelse(is.na(x$Planned), "isNA", "notNA")

Upvotes: 1

Related Questions