-1

I have this variable month and I want to assign corresponding numbers by creating a new variable like:

Month    New variable
January             1
February            2
April               4
March               3

I wanted to use ifelse but i got 4 conditions

here my initial code:

df$newvar=ifelse(df$month=="March"& df$month=="April",3,4)
camille
  • 16,432
  • 18
  • 38
  • 60
p1077092
  • 1
  • 2
  • It does'nt work.It was an example.My month variable look like this:Mar Mar Mar Apr Apr Jan Jan ... – p1077092 Nov 29 '21 at 01:25
  • 1
    `df$month=="March"& df$month=="April"` isn't going to evaluate to true anywhere, since you're checking that the month is both March & April – camille Nov 29 '21 at 01:25
  • usually I use ifelse to assign values with 2 conditions like 0 or 1,but this time i want use for 4 conditions 1,2,3,4 – p1077092 Nov 29 '21 at 01:31
  • If they are abbreviations, could you use `match(df$month, month.abb)`? – Ben Nov 29 '21 at 01:43

3 Answers3

0

Make a second dataframe with the month names and their numbers, then merge.

df1 <- data.frame(Month = c("January", "February", "March", "April"))
df2 <- data.frame(Month = month.name, New = 1:12)

merge(df1, df2, sort = FALSE)

Result:

     Month New
1  January   1
2 February   2
3    March   3
4    April   4
neilfws
  • 32,751
  • 5
  • 50
  • 63
-1

you can use a mapping of month to number, so it is not necessary to use if-else,

library(dplyr)
df <- data.frame( Month = c("January", "February", "April","March"))
months_number <- list(January=1,February=2,April=4,March=3)


df <- df %>% mutate(new_var=recode(Month,!!!months_number)) 
df
jwzinserl
  • 427
  • 1
  • 3
  • 7
-2

dplyr::case_when solution

df <- data.frame(
  Month = c("January", "February", "April", "March")
)
df %>%
  mutate(New_var = case_when(
    Month == "January" ~ 1,
    Month == "February" ~ 2,
    Month == "April" ~ 4,
    Month == "March" ~ 3,
    TRUE ~ NA_real_
  ))

     Month New_var
1  January       1
2 February       2
3    April       4
4    March       3
Park
  • 14,771
  • 6
  • 10
  • 29
  • This seems really inefficient, if not from a performance standpoint then just from the amount of typing and potential for typos. If you're going to match values from a single column/vector, why not just use something like `match`? Especially considering that R comes with a built-in table of month names and numbers to avoid doing something like this – camille Nov 29 '21 at 19:29
  • @camille I was not sure if it's typo or not. – Park Nov 30 '21 at 00:13
  • Not sure if what's a typo? – camille Nov 30 '21 at 00:46
  • @camille I'm sorry. I though it was typo, February. I'm not good at english.... – Park Nov 30 '21 at 01:02
  • 1
    Ah, okay. No, unfortunately February is one of many words in English whose spelling makes no sense; the OP has it spelled correctly – camille Nov 30 '21 at 02:57