Reputation: 55
I have a table like :
Fish Group Position
1 1 100
2 1 250
3 1 500
4 2 25
5 2 75
6 2 625
I have groups of fish with their position in the stream. To know how close they are, on average, I need to calculate the mean of the difference of distances for all observations within groups.
For fish of group 1, it does:
1-2 distance = 250 - 100 = 150
2-3 distance = 500 - 250 = 250
3-1 distance = 500 - 100 = 400
So the mean I look for is mean(150 + 250 + 400)
The tricky thing for me is to find a way to do it in the tidyverse philosophy !
Upvotes: 1
Views: 661
Reputation: 39595
If DF
is your data you can try this. Hope it can help:
library(dplyr)
DF %>% group_by(Group) %>% mutate(Diff=c(last(Position)-first(Position),diff(Position)))
# A tibble: 6 x 4
# Groups: Group [2]
Fish Group Position Diff
<int> <int> <int> <int>
1 1 1 100 400
2 2 1 250 150
3 3 1 500 250
4 4 2 25 600
5 5 2 75 50
6 6 2 625 550
As long as previous solution is just a sketch, try this modification and see if this applies for your original data:
#Create list by group
L <- split(DF,DF$Group)
#Create function
compute_d <- function(x)
{
xv <- as.numeric(x$Position)
y <- dist(xv)
return(y)
}
#Apply function
lapply(L,compute_d)
The results:
$`1`
1 2
2 150
3 400 250
$`2`
1 2
2 50
3 600 550
Or even more modified (new version):
#Create list by group
L <- split(DF,DF$Group)
#Create function
compute_d <- function(x)
{
xv <- as.numeric(x$Position)
y <- dist(xv)
avg <- mean(y)
y1 <- as.data.frame(as.matrix(y))
y2 <- cbind(x,y1)
y2$mean <- avg
return(y2)
}
#Apply function
z <- do.call('rbind',lapply(L,compute_d))
rownames(z)<-NULL
Fish Group Position 1 2 3 mean
1 1 1 100 0 150 400 266.6667
2 2 1 250 150 0 250 266.6667
3 3 1 500 400 250 0 266.6667
4 4 2 25 0 50 600 400.0000
5 5 2 75 50 0 550 400.0000
6 6 2 625 600 550 0 400.0000
Upvotes: 1