I have a data set with two columns that I would like to combine into a single column using dplyr rowwise mutate and a custom function. Strangely for the second row matching a certain pattern (but not the first or subsequent) I get NA as a return value. Below is an example:
my.func <- function(alpha, beta) {
if(!is.na(beta) & beta) {
return("c")
} else if(is.na(alpha)) {
return(as.character(NA))
} else if (alpha == "a") {
return("a")
} else if (alpha == "b") {
return("b")
} else {
return(as.character(NA))
}
}
tmp <- data.frame(obs = 1:7,
dt = c('2016-03-15 17:35:46','2016-03-15 18:45:47','2016-03-15 19:22:17','2016-03-15 19:23:45','2016-03-15 20:21:55','2016-03-15 21:20:10','2016-03-15 22:18:34'),
one = c(NA,"a","a","a","b","a","b"), two = c(NA,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE))
tmp2 <- tmp %>% rowwise() %>% mutate(three = my.func(one, two))
This results in an NA in row three, column three, when for the row above, with the exact same input, it resulted in "a".
mapply(my.func, tmp$one, tmp$two)
provides the correct result. And if you change the firstNA
it becomes right as well... Maybe it has something to do withrowwise()
. – Alex