我需要做的是计算连续线之间的差异。 有一个聪明的方法吗? 以下解决方案有效。感谢
pos=data.frame(position=c(1,2,3),value=c(1.3,2.7,3.1))
position value
1 1 1.3
2 2 2.7
3 3 3.1
r=NULL; rnome=NULL
for(i in seq(1,length(pos[,1])-1))
for(j in seq(i+1,length(pos[,1])))
r=rbind(r,c(levels=paste0(pos$level[i],'-', pos$level[j]), dif=pos$value[j]-pos$value[i]))
> r
levels dif
[1,] "1-2" "1.4"
[2,] "1-3" "1.8"
[3,] "2-3" "0.4"
答案 0 :(得分:1)
combn
函数可以帮助您稍微概括一下代码。这看起来更优雅:
pos <- data.frame(position=c(1,2,3),value=c(1.3,2.7,3.1))
ans <- data.frame(levels = combn(pos$position, 2, FUN = paste, collapse = "-"),
dif = combn(pos$value, 2, FUN = diff))
print(ans)
# levels dif
#1 1-2 1.4
#2 1-3 1.8
#3 2-3 0.4
# Get all combinations:
comb <- expand.grid(pos$position, pos$position)
lvls <- with(comb, paste0(Var1, "-", Var2))
difs <- with(comb, Var1 - Var2)
ans2 <- data.frame(levels = lvls, dif = difs)
print(ans2)
# levels dif
#1 1-1 0
#2 2-1 1
#3 3-1 2
#4 1-2 -1
#5 2-2 0
#6 3-2 1
#7 1-3 -2
#8 2-3 -1
#9 3-3 0