I created a simple function that has ifelse
, and would like to use multiple dataframe columns as its input. Here is what I did.
year <- c(2016, 2016, 2017, 2017)
month <- c(11, 12, 1, 2)
df <- data.frame(year, month)
test_1 <- function(n, year_2016 = FALSE, year_2017 = FALSE){
return ( ifelse( (year_2016 == FALSE && year_2017 == FALSE), ifelse(n==24, 'a', 'b'), ifelse(year_2016 == TRUE, ifelse(n==24, 'c', 'd'), ifelse(n==24, 'e', 'f'))))
}
test_2 <- function(n, year_2016 = FALSE){
return (ifelse(year_2016 == FALSE, ifelse(n==12, 'g', 'h'), ifelse(n==12, 'i', 'j')))
}
test_1
outputs only a single value from the first row, while test_2
outputs the vector. I was thinking both should be vectors.
If anyone can guide me why this is happening, that would be great. Also, if there's a better way to do this vector calculation, please advice.
Thanks!
=====================================
edit:
Sorry, that I didn't include the line actually running the function. I ran the two followings, which I was hoping to get vectors in both.
test_1(df$month, df$year == 2016, df$year == 2017)
test_2(df$month, df$year == 2016)
However, when I run it, I get the following.
test_1(df$month, df$year == 2016, df$year == 2017)
[1] "d"
test_2(df$month, df$year == 2016)
[1] "j" "i" "h" "h"