# Mutate with custom function in R does not work

I have a data frame, containing a column called: "Frequency". Frequency has values like "Year", "Week", "Month" etc. Now I want to create a new column based on the Frequency column where Year's new corresponding value will be 1, Month's corresponding value will be 12 and Week corresponding value will be 48. I tried to make a function for this as "getValue" and tried to make a new column applying a mutation (dplyr) on that funcion. But unfortunately I am getting the following warning and all values being transformed by the value of "1".

getValue <- function(input) {

if (input == 'Year')
{
result <- 1
}
else if(input == 'Month')
{
result <- 12
}
else if(input == 'Week')
{
result <- 48
}

return(result)
}

Data =  mutate(gateway, YearlyHit = getValue(gateway$Frequency)) Data  Here is the warning message I am getting - Warning message: In if (input == "Year") { : the condition has length > 1 and only the first element will be used  How can I achieve the required result in R? ## 3 Answers Why don't you solve it in this way? mutate(gateway, YearlyHit = case_when(Frequency == 'Year' ~ 1, Frequency == 'Month' ~ 12, Frequency == 'Week' ~ 48) )  The function you are passing to mutate, getValue doesn't understand vector data. Try: v_getValue <- Vectorize(getValue) Data = mutate(gateway, YearlyHit = v_getValue(gateway$Frequency))


More detail here

My question was solved by the following command:

gateway$$newcol <- mapply(getValue, gateway$$Frequency)


Data =  mutate(gateway, YearlyHit = getValue(gateway\$Frequency))