'Assigning std::minmax result to new variables
auto [x, y] = std::minmax(a, b) defines x and y as references to a and b (or b and a).
How do I make x and y new variables initialized with min and max values respectively (as if minmax returned pair of values instead of pair of refs)?
Solution 1:[1]
Using substr, substring.
df <- transform(df, Yrmo_half=paste0(substr(date, 1, 8),
ifelse(as.numeric(substring(date, 9)) > 15,
'half_2', 'half_1')))
df[8:18, ]
# date x Yrmo_half
# 8 2021-12-20 0.1639289 2021-12-half_2
# 9 2021-12-19 0.4417741 2021-12-half_2
# 10 2021-12-18 0.5234077 2021-12-half_2
# 11 2021-12-17 0.4769192 2021-12-half_2
# 12 2021-12-16 0.5246433 2021-12-half_2
# 13 2021-12-15 0.6852282 2021-12-half_1
# 14 2021-12-14 0.3517920 2021-12-half_1
# 15 2021-12-13 0.8396313 2021-12-half_1
# 16 2021-12-12 0.9219137 2021-12-half_1
# 17 2021-12-11 0.1063096 2021-12-half_1
# 18 2021-12-10 0.2065289 2021-12-half_1
Solution 2:[2]
One way would be the following:
df$Yrmo_half <- ifelse(as.integer(format(df$date, '%d')) < 15,
paste0(format(df$date, '%y-%m'), '-half_1'),
paste0(format(df$date, '%y-%m'), '-half_2'))
which will yield:
# date x Yrmo_half
# 1 2021-12-27 0.1931067 21-12-half_2
# 2 2021-12-26 0.1684232 21-12-half_2
# 3 2021-12-25 0.1118781 21-12-half_2
# 4 2021-12-24 0.4864917 21-12-half_2
# 5 2021-12-23 0.9466433 21-12-half_2
# 6 2021-12-22 0.5007273 21-12-half_2
Solution 3:[3]
Here's a regex solution:
library(dplyr)
library(stringr)
df %>%
mutate(
# create temporary column `temp` with day value:
temp = as.numeric(str_extract(date, "\\d+$")),
# convert `temp` value to "half_1" or "half_2" value:
temp = ifelse(temp <= 15, "half_1", "half_2"),
# extract year-month value and collate with `temp` value:
Yrmo_half = str_c(str_extract(date, "[0-9-]+-"), temp)) %>%
# remove temporary column:
select(-temp)
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 | jay.sf |
| Solution 2 | AlexB |
| Solution 3 | Chris Ruehlemann |
