create a new column with the values of another?

Hi everyone,

do you know how can i create a new column with the values of another?

this is my dataframe

structure(list(weeks = c(1, 5, 2, 3, 6, 4, 8, 12, 53, 52, 12,
6, 35, 45, 50), time = c(1, 4, 1, 2, 5, 3, 7, 11, 52, 50, 11,
5, 20, 40, 49)), class = "data.frame", row.names = c(NA, 15L))

and this is what i want to get:

structure(list(weeks = c(1, 5, 2, 3, 6, 4, 8, 12, 53, 52, 12,
6, 35, 45, 50), QT = c("Q1", "Q1", "Q1", "Q1", "Q1", "Q1", "Q1",
"Q1", "Q4", "Q4", "Q1", "Q1", "Q3", "Q4", "Q4"), time = c(1,
4, 1, 2, 5, 3, 7, 11, 52, 50, 11, 5, 20, 40, 49)), class = "data.frame", row.names = c(NA,
15L))

and this is my code:

 
w |> 
  mutate(QT=case_when (w$weeks(1%in%12)~Q1,
                       w$weeks(13%in%25)~Q2,
                       w$weeks(26%in%39)~Q3,
                       w$weeks(40%in%53)~Q4
                       ))

i get this error:

Error in mutate(w, QT = case_when(w$weeks(1 %in% 12) ~ Q1, w$weeks(13 %in% :

Caused by error:
! attempt to apply non-function

thanks in advance

Not sure why I cannot run it with the native pipe (haven't used it before), but with the one from tidyverse it could be done like this:

w  %>%  
  mutate(QT=case_when(weeks >= 1 & weeks <= 12 ~ "Q1",
                      weeks >= 13 & weeks <= 25 ~ "Q2",
                      weeks >= 26 & weeks <= 39 ~ "Q3",
                      weeks >= 40 & weeks <= 52 ~ "Q4" ))

Moreover, as the case_when works sequentially, and only 1 value can be attributed, the first hit is used, so we can simplify it a bit more:

w  %>%  
  mutate(QT=case_when(weeks >= 40 ~ "Q4",
                      weeks >= 26 ~ "Q3",
                      weeks >= 13 ~ "Q2",
                      TRUE ~ "Q1" ))

Q1, Q2... are strings and should be put into quotation marks,
the w$ isn't needed as the dataframe (w) is sent in via the pipe,
(1%in%12) just didn't work this way.
%in% 1:12 would be another option, catching the mistake as well...

w  %>%  
  mutate(QT=case_when(weeks %in% 1:12 ~ "Q1",
                      weeks %in% 13:25 ~ "Q2",
                      weeks %in% 26:39 ~ "Q3",
                      weeks %in% 40:52 ~ "Q4" ))
1 Like

Thanks Matthias,

it works perfectly!! :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.