I can write this code that adds two columns to the iris data set. The first added column is a sum of the first four columns. The second added column is my attempt at "programming".
iris.size <- iris %>%
mutate(Total =
apply(.[(1:4)], 1, sum)
) %>%
mutate(Size =
ifelse(
apply(.[(1:4)], 1, sum) != 0 &
.[2] > .[3], "Output1",
ifelse(
apply(.[(1:4)], 1, sum) == 0 &
.[2] > .[3], "Output2",
"Output3")
)
)
You'll notice this code does not throw any errors and it does output what I want it to output. But watch what happens when I try my next step in analysis.
iris.size %>% arrange(Size)
Error: Column
Size
must be a 1d atomic vector or a list
It must be my ifelse logic. Correct? Ifelse logic seems straightforward. If condition 1 than output1
, otherwise if condition 2 than output2
, otherwise output3
.
I ended up forcing iris.size$Size into a vector using as.vector
but I'd like to know where my logic went wrong in the first place so I don't have to resort to using band aids in the future. After some googling it sounds like if
statements are preferred over ifelse
statements in R, but if
statements only seem to work on single logical values, not vectors.