Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 确定分组数据帧中的较低值和较高值_R_Tidyverse - Fatal编程技术网

R 确定分组数据帧中的较低值和较高值

R 确定分组数据帧中的较低值和较高值,r,tidyverse,R,Tidyverse,我有一个以下格式的数据帧: pair_id group_id value <int> <int> <dbl> 1 1 0.600 1 2 0.400 2 3 0.500 2 4 0.500 3 5 0.200 3 6 0.800 4 7 0.300

我有一个以下格式的数据帧:

 pair_id group_id value
 <int>    <int>   <dbl>
    1        1    0.600
    1        2    0.400
    2        3    0.500
    2        4    0.500
    3        5    0.200
    3        6    0.800
    4        7    0.300
    4        8    0.700
    5        9    0.500
    5       10    0.500
pair\u id group\u id值
1        1    0.600
1        2    0.400
2        3    0.500
2        4    0.500
3        5    0.200
3        6    0.800
4        7    0.300
4        8    0.700
5        9    0.500
5       10    0.500
它由以下代码段生成:

library(tidyverse)

df <- tibble(pair_id = rep(1:5, each = 2),
             group_id = seq(1:10),
             value = c(0.6, 0.4, 0.5, 0.5, 0.2, 0.8, 0.3, 0.7, 0.5, 0.5))
库(tidyverse)

df按“pair_id”分组后,在“value”列上使用
which.min
which.max
,以获得相应“group_id”子集的行索引

df %>% 
  group_by(pair_id) %>% 
  summarise(groupMin = group_id[which.min(value)], groupMax = group_id[which.max(value)])
df %>%
   group_by(pair_id) %>%
   summarise(groupMin = sample(group_id[value == min(value)], 1),
             groupMax = sample(group_id[value == max(value)], 1) )
注意:如果“配对id”有多个
min
max
值,则
which.min
which.max
仅获取第一个索引


如果存在多个
min
max
值,则使用
=
样本
获取
随机
组id

df %>% 
  group_by(pair_id) %>% 
  summarise(groupMin = group_id[which.min(value)], groupMax = group_id[which.max(value)])
df %>%
   group_by(pair_id) %>%
   summarise(groupMin = sample(group_id[value == min(value)], 1),
             groupMax = sample(group_id[value == max(value)], 1) )
更新 根据OP的意见,如果“值”中的不同元素的数量等于1,则我们
按“pair_id”和“value”降序排列
,按“pair_id”分组,然后通过
示例
ing或
其他
按“higher”和“lower”的顺序分配“higher”、“lower”值

df%>%
排列(对id,描述(值))%>%
分组依据(配对id)%>%
变异(当(n_不同(值)==1~样本(c(“较高”、“较低”))时,组秩=案例),
真~c(“更高”、“更低”))
#一个tibble:10x4
#组:配对id[5]
#配对\u id组\u id值组\u秩
#                
#10.600以上
#2 1 2 0.400以下
#3200.500以上
#4 2 0.500以下
#5360.800以上
#6 3 5 0.200以下
#7480.700以上
#8 4 7 0.300以下
#95.500以下
#105010.500以上

非常感谢您的回复。我更新了我的问题,因为它似乎有点不清楚。我添加了一个目标数据框来说明我的目标。最终的目标是根据设定的需求生成具有“更高”或“更低”的数据帧。基本上,我正在寻找一种方法来立即分配这些类别。我希望“较高”或“较低”的随机分配仅在具有相同值的成对中进行,例如,其中min==max。在所有其他情况下,我希望分配以值是max还是min为基础。@HristoHristov更新了帖子,非常感谢您的回答!