[英]R: How to to replace(switch) the max and min values in a row in a dataframe when max <= min?
How we can replace(switch) the max and min values in each row in this dataframe ONLY if max <= min ?仅当 max <= min 时,我们如何才能替换(切换)此数据帧中每一行的最大值和最小值?
> my_data
year month day max min
1 2019 1 1 20.4 -24.4
2 2019 1 2 12.9 -20.4
3 2019 1 3 -27.1 10.3
4 2019 1 4 -20.8 11.0
5 2019 1 5 -16.2 -8.9
The result should be like this:结果应该是这样的:
> my_data
year month day max min
1 2019 1 1 20.4 -24.4
2 2019 1 2 12.9 -20.4
3 2019 1 3 10.3 -27.1
4 2019 1 4 11.0 -20.8
5 2019 1 5 -8.9 -16.2
Thanks in advance.提前致谢。
One option is pmax/pmin
一种选择是
pmax/pmin
library(dplyr)
my_data %>%
mutate(maxnew = pmax(max, min), minnew = pmin(max, min)) %>%
select(year, month, day, max = maxnew, min = minnew)
# year month day max min
#1 2019 1 1 20.4 -24.4
#2 2019 1 2 12.9 -20.4
#3 2019 1 3 10.3 -27.1
#4 2019 1 4 11.0 -20.8
#5 2019 1 5 -8.9 -16.2
Or a compact way is with base R
或者一种紧凑的方式是使用
base R
nm1 <- c('max', 'min')
my_data[nm1] <- t(apply(my_data[nm1], 1, sort))[, 2:1]
Or using pmax/pmin
或使用
pmax/pmin
my_data[nm1] <- lapply(list(pmax, pmin), function(f) do.call(f, my_data[nm1]))
my_data <- structure(list(year = c(2019L, 2019L, 2019L, 2019L, 2019L), month = c(1L,
1L, 1L, 1L, 1L), day = 1:5, max = c(20.4, 12.9, -27.1, -20.8,
-16.2), min = c(-24.4, -20.4, 10.3, 11, -8.9)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))
We can find the index where max
is less than min
.我们可以找到
max
小于min
的索引。 Store those max
values in temporary variable and then swap the max and min values using that.将这些
max
存储在临时变量中,然后使用它交换最大值和最小值。
inds <- df$max < df$min
temp <- df$max[inds]
df$max[inds] <- df$min[inds]
df$min[inds] <- temp
df
# year month day max min
#1 2019 1 1 20.4 -24.4
#2 2019 1 2 12.9 -20.4
#3 2019 1 3 10.3 -27.1
#4 2019 1 4 11.0 -20.8
#5 2019 1 5 -8.9 -16.2
data数据
df <- structure(list(year = c(2019L, 2019L, 2019L, 2019L, 2019L), month = c(1L,
1L, 1L, 1L, 1L), day = 1:5, max = c(20.4, 12.9, -27.1, -20.8,
-16.2), min = c(-24.4, -20.4, 10.3, 11, -8.9)), class = "data.frame",
row.names = c("1", "2", "3", "4", "5"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.