-1

1-) If I have a column that represents months (M1, M2, M3, M4.. M12 ... M1, M2, ...), how to use a function that replace each one to (01, 02, 03, 04...) ? I have tried to use mutate and replace together , but no success. It just worked with ifelse function, but it's very large.

My second question:

If I have a column that has a lot of character names, how do I filter more than 10 names inside this column ?

I have tried filter(column== c("xx", "xy" ...)), but the filter result was incorrect and I got this message: longer object length is not a multiple of shorter object length

Gui_99
  • 51
  • 7
  • When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Mar 29 '18 at 19:26
  • For question 2 take a look at the `%in%` or `match()` functions. – Dave2e Mar 29 '18 at 19:33

1 Answers1

1

You can change your months using recode() within mutate() like so:

dat %>% 
  mutate(month_column = recode(month,
                               "M1" = "01",
                               "M2" = "02",
                               ...
                               "M12" = "12"))

Note that I input them as strings because that's how you get the leading zeroes.

Your second question is unclear, but it seems what you want to do is have a list of 10 names (of 10+n names in total) and subset to only those? If that's the case, you can use filter() with the %in% operator.

dat %>%
  filter(name_column %in% c("xx", "xy", ... ))

You could also extract the vector outside of the piping:

vector_of_names <- c("xx", "xy", ... )
dat %>% filter(name_column %in% vector_of_names)

If you combine that all it should look like this:

dat %>%
  filter(name_column %in% c("xx", "xy", ... )) %>%
  mutate(month_column = recode(month,
                               "M1" = "01",
                               "M2" = "02",
                               ...
                               "M12" = "12"))
cparmstrong
  • 799
  • 6
  • 23