首页 > 解决方案 > 如何重复对数据进行子集化并跨 R 中的列执行函数?

问题描述

我希望在一列中选择具有相同标签的样本,并在具有相同标签的组中对该组的最大和最小距离数(距离数是不同列中的样本数据)执行减法,但是我不知道如何选择一列中具有重复标签的样本,然后根据其他列中的数据执行减法。

我的数据如下所示:

Start number  End Number Region label 
     1            2        A
     3            4        A
     5            6        B

我正在尝试为要选择的区域 A 样本和要完成的 4-1=3 编码(从最大结束数中减去最小开始数),并为每个区域重复此操作。所以它会输出这个:

Start number  End Number Region label   Total region distance
     1            2        A                  3
     3            4        A                  3
     5            6        B                 ...

目前我已经尝试使用该match()功能选择重复项然后使用min(df$Start.number)max(df$End.number)但是我不确定如何使这项工作正常工作并为每个区域重复。

我也尝试过查看类似的问题并应用他们的答案,但我得到了错误:

library(dplyr)
library(tidyr)

df$distance <- NA 
df %>%
    gather(key, value, -region) %>%
    group_by(region) %>%
    df$distance = max(df$Start) - min(df$End) 

Error in df %>% gather(key, value, -region) %>% group_by(region) %>% df$distance = max(df$Start) -  : 
  could not find function "%>%<-"
In addition: Warning message:
attributes are not identical across measure variables;
they will be dropped 

标签: r

解决方案


在您使用 时dplyr,最后一行出现错误。要定义新列,您必须使用mutate如下

df = data.frame(labels = c("A","A","B"),
                s = c(1,3,5),
                e = c(2,4,6))

df %>% group_by(labels) %>% mutate(Diff = max(e) - min(s)) 

# A tibble: 3 x 4
# Groups:   labels [2]
  labels     s     e  Diff
  <fct>  <dbl> <dbl> <dbl>
1 A          1     2     3
2 A          3     4     3
3 B          5     6     1

如果您想将所有这些操作传递到您的数据框中并获得一个新列Diff,您必须执行以下操作:

df <- df %>% group_by(labels) %>% mutate(Diff = max(e) - min(s)) 

推荐阅读