我有一个数据框,其中每一行表示值随时间的变化:在数据框的每个单元格中,值可能会或可能不会在潜在的大量列上一列接一列地改变.
Goal个 最终目标是获得表示这些值随时间从一列变化到相邻一列(即COL1->COL2、COL2->COL3、COL3->COL4等)的值对的完整序列.
现在,我用for
循环遍历数据帧列和select
2个连续的col',rbind
个这些值一起,如果需要的话,filter
个结果(见下面的最小示例).
Question有没有比我的for
循环更好的解决方案,或者甚至有专门迭代成ol‘的函数?
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)
说