r - 如何重复对数据进行子集化并跨 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
解决方案
在您使用 时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))
推荐阅读
- python - 如何连接文件夹中每个 .xlsx 文件的第二张纸?
- c# - 如何检查 BindingContext 中是否存在某些东西?
- kotlin - 在有根的 android 设备中创建原始套接字时“不允许操作”。java的UID是root,c代码的UID不是root
- webpack - Webpack 开发服务器如何使用构建目录中没有文件的包?
- excel - 用户到基于 Excel 的组
- javascript - React JS如何根据检查值数组检查一些复选框
- angularjs - D3 js单击时反转过渡
- reactjs - React.createElement:将反应组件捆绑并导入另一个反应应用程序后,类型无效错误
- docker - 如何通过 Traefik 在 Docker 中代理 Gitlab
- javascript - 使用 Vuejs 从 GoogleMaps 实现 fitBounds