I have 1 data frame, I want to to go from A to F by following sequence of A-B-C-D-E-F. How to proceed using R.
> m
V1 V2 V3
1 A B 0.1
2 B C 0.2
3 C D 0.3
4 D E 0.2
5 E F 0.5
I have 1 data frame, I want to to go from A to F by following sequence of A-B-C-D-E-F. How to proceed using R.
> m
V1 V2 V3
1 A B 0.1
2 B C 0.2
3 C D 0.3
4 D E 0.2
5 E F 0.5
The way I understand your comments, the relationship between A and F is the product of m$V3 between their rows.
af <- function(from, to){
x <- which(m$V1 == from)
y <- which(m$V2 == to)
return(prod(m$V3[x:y]))
}
af("A", "F")
[1] 6e-04
Then, F = A * 0.0006.
To generalize to any sequence and any row order in the table, we first define the sequence.
sq <- c("A", "B", "C", "D", "E", "F") # or LETTERS[1:6] in this case
Within the function, we select the respective rows as those, where both columns V1 and V2 contain sequence conditions that match the specification.
af2 <- function(from, to){
cond <- sq[which(sq == from):which(sq == to)]
x <- m$V1 %in% cond & m$V2 %in% cond
return(prod(m$V3[x]))
}
Test
Using the original matrix, both functions provide identical results.
af("B","E")
[1] 0.012
af2("B","E")
[1] 0.012
When we randomise row order, only the second function returns the correct result.
set.seed(123456)
m <- m[sample(1:5),]
m
V1 V2 V3
4 D E 0.2
5 E F 0.5
2 B C 0.2
1 A B 0.1
3 C D 0.3
af("B","E")
[1] 0.02
af2("B","E")
[1] 0.012