我正在计算我们在trap 中捕捉小龙虾的距离的中值.我们有多年的trap 池塘,并知道我们设置的trap 数量和trap 的数量.
这是一个例子,我正在努力做什么.
# Create vectors for each column
Pond <- c("Aubrees", "Aubrees", "Kohls", "Kohls")
Year <- c(2019, 2020, 2019, 2020)
TrapNumbers <- list(c(1, 9, 2, 3, 6), c(3, 4, 9, 2, 5), c(3, 4, 9, 2), c(1, 9, 2, 3))
NumberofTraps <- c(10, 10, 12, 12)
# Initialize an empty vector to store all TrapCaught values
TrapCaught <- numeric()
# Iterate over the lists of TrapNumbers to combine them into one vector
for (trap_list in TrapNumbers) {
TrapCaught <- c(TrapCaught, trap_list)
}
# Create the dataframe
DF <- data.frame(Pond = rep(Pond, sapply(TrapNumbers, length)),
Year = rep(Year, sapply(TrapNumbers, length)),
NumberofTraps = rep(NumberofTraps, sapply(TrapNumbers, length)),
TrapCaught = TrapCaught)
NumberofTraps列告诉我有多少个trap 设置在池塘中,在海岸线周围呈圆形排列.所以在一个有10个trap 的池塘里,1和9之间的距离是2而不是8.我也不想计算一个点和它自身之间的距离.当我为这些手动操作时,我找到了这些值的距离和中值的池塘和年份.
Aubrees 2019 中位距离:2,1,2,5,3,4,3,1,4,3 平均值=3
Aubrees 2020 中位距离:1,4,1,2,5,2,1,3,4,3 平均值=2.5
Kohls 2019 中间距离:1,6,1,5,2,5 中位数= 3.5
Kohls 2020 中间距离:4,1,2,5,6,1 中位数= 3
我有这个代码,我正在try ,但我没有得到期望值.
library(dplyr)
# Function to calculate pairwise distances between two vectors
pairwise_distances <- function(x) {
n <- length(x)
outer(x, x, "-") %% n
}
# Calculate the median distance for each group
median_distances <- DF %>%
group_by(Pond, Year) %>%
summarize(median_distance = median(pairwise_distances(TrapCaught)[upper.tri(pairwise_distances(TrapCaught))]))
# Print the result
print(median_distances)
The values output are:
Pond: Aubrees, Aubrees, Kohls, Kohls
Year: 2019, 2020, 2019, 2020
Code Median Output: 2, 2.5, 2.5. 2.5
Expected Median Outcome: 3, 2.5, 3.5, 3