r - 给定 R 中另一个变量的条件,你能从一个变量中提取最小值吗?
问题描述
假设我有来自 min 的数据。下面的可重现示例。我想用 ready.data 中的 ready.data$RetAge 的最小值更新 MinReadyAge 变量,其中 ready.data$Ready == 'Yes'。有没有一种有效的方法来做到这一点?
对于任何年龄都没有“是”的情况,如果有办法返回“从未准备好”,则可获得奖励积分。
ID <- c(1,2,3,4,5)
MinReadyAge <- 1:5
min.age.data <- as.data.frame(cbind(ID,MinReadyAge))
ID <- c(1,1,1,1,1,
2,2,2,2,2,
3,3,3,3,3,
4,4,4,4,4,
5,5,5,5,5)
RetAge <- rep(seq(from = 65, to = 69, by = 1),5)
Ready <- c("No","No","No","No","No",
"No","No","No","No","Yes",
"No","No","No","Yes","Yes",
"No","No","Yes","Yes","Yes",
"Yes","Yes","Yes","Yes","Yes")
ready.data <- as.data.frame(cbind(ID,RetAge,Ready))
解决方案
我们可以在通过“ID”获取“RetAge”slice
的min
值后对“min.age.data”进行连接,其中“Ready”为“Yes”
library(dplyr)
ready.data %>%
filter(Ready == 'Yes') %>%
group_by(ID) %>%
slice_min(RetAge) %>%
ungroup %>%
select(ID, MinRetAge = RetAge) %>%
right_join(min.age.data) %>%
arrange(ID)
# A tibble: 5 x 3
# ID MinRetAge MinReadyAge
# <dbl> <dbl> <int>
#1 1 NA 1
#2 2 69 2
#3 3 68 3
#4 4 67 4
#5 5 65 5
如果我们需要更新“MinRetAge”列
min.age.data <- ready.data %>%
filter(Ready == 'Yes') %>%
group_by(ID) %>%
slice_min(RetAge) %>%
ungroup %>%
select(ID, RetAge) %>%
right_join(min.age.data) %>%
transmute(ID, MinReadyAge = coalesce(RetAge, MinReadyAge)) %>%
arrange(ID)
-输出
min.age.data
# A tibble: 5 x 2
# ID MinReadyAge
# <dbl> <dbl>
#1 1 1
#2 2 69
#3 3 68
#4 4 67
#5 5 65
数据
# // as.data.frame(cbind is not needed and it will unnecessarily chage the type
# // cbind by default returns a matrix and matrix can have only a single type
# // instead using data.frame directly
ready.data <- data.frame(ID, RetAge, Ready)
min.age.data <- data.frame(ID, MinReadyAge)
推荐阅读
- c# - 如何在应用程序关闭之前杀死所有正在运行的线程?
- nestjs - 使用 NestJS 向响应添加状态
- python - 当我在烧瓶中调用函数时,语音识别不起作用
- powershell - 安装NewSSHSession离线服务器-powershell
- vue.js - VueJs:根据条件禁用特定日期之前的所有日期
- html - 带有 :before 伪元素的可编辑 div 中的光标位置
- pytorch - 如何定义带有拥抱面变压器管道的摘要配给?
- javascript - 如果删除了静音视频标签将无法播放
- python-3.x - 直接到烧瓶中的 Google 存储桶
- string - Perl 函数用 start、end 和 step 对字符串进行切片