Situation I have a data frame where each row expresses a change in values over time: in each cell of the data frame, values may or may not change columns after columns, over a potentially large number of col'.
Goal The final objective is to obtain a complete sequence of pairs of values that express these change over the time, from one col to the adjacent one (i.e. col1 -> col2, col2 -> col3, col3 -> col4, etc.).
For now, I iterate with a for
loop through the data frame columns and select
2 successive col', rbind
these values together, and filter
the result if I needed (see minimal example here-after).
Question Is there a better solution than my for
loop, or even a function dedicated to iterate into col'?
Current Approach
# Fake-dataframe ↓
test = data.frame(var1 = 2:5,
var2 = c(1, 3:5),
var3 = c(1,3,4 , 8),
var4 = c(2:4, 8)
)
require(tidyverse)
cn <- colnames(test)
graph = data.frame(from = NA, to = NA, name = NA)
# Iterate into 'test' col and construct paired list of value ↓
for (i in 1:(ncol(test) - 1)) {
graph <- rbind(graph,
select(test,
from = i,
to = i + 1
) %>%
mutate(name = cn[i+1])
)
}
graph <- na.omit(graph)
# Then I'll use some filter if I want to track change, e.g., filter(graph, from != to)
`