'How to change values in the dataset in R?

I need to calculate the average waste generated per week. But as seen in the dataset below. Some of the data is collected on a fortnightly basis and some on a weekly basis.

My Logic is that: I will simply multiply the weight by 2 if the Schedule is "Fortnightly B Friday" or "Fortnightly A Tuesday" or "Fortnightly B Monday". But how do I code this in R? :(

Here is a garbage collection dataset showing the Schedule of the collection and weight of the waste collected

r


Solution 1:[1]

You can use multiple cases with case_when().

x <- 1:50
case_when(
  x %% 35 == 0 ~ "fizz buzz",
  x %% 5 == 0 ~ "fizz",
  x %% 7 == 0 ~ "buzz",
  TRUE ~ as.character(x)

Solution 2:[2]

But how do I code this in R?

You didn't provide a reproducible example, so here is a data frame with dummy data that represents your data:

waste_data <- structure(list(Schedule = c("Every Friday", "Fortnightly B Friday", 
"Fortnightly A Tuesday", "Every Tuesday", "Every Tuesday", "Fortnightly A Tuesday", 
"Fortnightly B Monday"), Weight = 5:11), class = "data.frame", row.names = c(NA, 
-7L))

waste_data
#                Schedule Weight
# 1          Every Friday      5
# 2  Fortnightly B Friday      6
# 3 Fortnightly A Tuesday      7
# 4         Every Tuesday      8
# 5         Every Tuesday      9
# 6 Fortnightly A Tuesday     10
# 7  Fortnightly B Monday     11

To apply your logic on the data, you can create a new column and use ifelse or case_when to generate the column's elements. Say that your new columns is named TrueWeight:

Option 1

# Following @missuse's comments

waste_data$TrueWeight <- ifelse(grepl("^Fortn", waste_data$Schedule),  
                                2 * waste_data$Weight,  
                                waste_data$Weight)
waste_data
#                Schedule Weight TrueWeight
# 1          Every Friday      5          5
# 2  Fortnightly B Friday      6         12
# 3 Fortnightly A Tuesday      7         14
# 4         Every Tuesday      8          8
# 5         Every Tuesday      9          9
# 6 Fortnightly A Tuesday     10         20
# 7  Fortnightly B Monday     11         22

Option 2

# Following MIK's answer

waste_data <- waste_data |> 
       mutate(TrueWeight = case_when(
                                str_detect(Schedule, "^Fortn") ~ 2 * Weight,
                                TRUE ~ 1* Weight))
waste_data
#                Schedule Weight TrueWeight
# 1          Every Friday      5          5
# 2  Fortnightly B Friday      6         12
# 3 Fortnightly A Tuesday      7         14
# 4         Every Tuesday      8          8
# 5         Every Tuesday      9          9
# 6 Fortnightly A Tuesday     10         20
# 7  Fortnightly B Monday     11         22

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Abdur Rohman