0
$\begingroup$

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?

$\endgroup$
1
$\begingroup$

Why don't you solve it in this way?

mutate(gateway, YearlyHit = case_when(Frequency == 'Year' ~ 1,
                                      Frequency == 'Month' ~ 12,
                                      Frequency == 'Week' ~ 48)
)
$\endgroup$
0
$\begingroup$

My question was solved by the following command:

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

instead of:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.