Suppose I have a data frame:
mydf <- data.frame(colA = c(1,20), colB = c("a", "ab"), colC = c(T, F))
Now suppose I want to apply a function to each row on the data frame. This function uses the boolean value of column C. When using apply
, every non-string is converted to a string of the maximum length present in the column:
> apply(mydf, 1, '[', 3)
[1] " TRUE" "FALSE"
The string " TRUE"
is no longer interpretable as a logical.
> ifelse(apply(mydf, 1, '[', 3), 1, 2)
[1] NA 2
I could solve this with a gsub(" ", "", x)
, but I'd bet there is a better way. Why does apply
have this behavior when it could just directly convert the logicals to strings? Is there an apply
-like function which does not have the above behavior?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…