gpt4 book ai didi

r - 将成对的值分隔成单个变量的行/列

转载 作者:行者123 更新时间:2023-12-01 12:12:40 26 4
gpt4 key购买 nike

搜索过,但没看到在哪里处理过。我有一个项目站点之间绝对差异的成对计算数据框,数据是这样的

   x y value
1 2 1 5
2 3 1 4
3 4 1 6
4 5 1 3
5 3 2 5
6 4 2 7
7 5 2 3
8 4 3 2
9 5 3 5
10 5 4 7

其中 x 和 y 是配对站点,value 是差值。我想分别显示每个站点的平均值结果。例如。所有站点 5 对 (5|3, 5|4, 5|1, 5|2) = 4.5 的站点平均值,这样我的结果将如下所示:

site    avg 
1 4.5
2 5
3 4
4 5.5
5 4.5

谁得到了解决方案?

最佳答案

这是 tidyverse 的另一个选项

library(tidyverse)
df %>%
select(x, y) %>%
unlist %>%
unique %>%
sort %>%
tibble(site = .) %>%
mutate(avg = map_dbl(site, ~
df %>%
filter_at(vars(x, y), any_vars(. == .x)) %>%
summarise(value = mean(value)) %>%
pull(value)))
# A tibble: 5 x 2
# site avg
# <int> <dbl>
#1 1 4.5
#2 2 5
#3 3 4
#4 4 5.5
#5 5 4.5

数据

df <- structure(list(x = c(2L, 3L, 4L, 5L, 3L, 4L, 5L, 4L, 5L, 5L), 
y = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 4L), value = c(5L,
4L, 6L, 3L, 5L, 7L, 3L, 2L, 5L, 7L)), .Names = c("x", "y",
"value"), class = "data.frame",
row.names = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10"))

关于r - 将成对的值分隔成单个变量的行/列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50654522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com