1. 程式人生 > 其它 >R語言中提取多個連續值的累計的中間位點

R語言中提取多個連續值的累計的中間位點

1、R實現

test <- c(20,50,40,60,80)  ## 測試資料
coordinate <- vector()
base <- 0
temp <- 0
for (i in 1:length(test)) {
  temp <- base + 0.5 * test[i]
  coordinate <- c(coordinate,temp)
  base <- base + test[i]
}
coordinate
> test <- c(20,50,40,60,80)  ## 測試資料
> coordinate <- vector()     ## 建立空向量
> base <- 0 > temp <- 0 > for (i in 1:length(test)) { + temp <- base + 0.5 * test[i] ##在基礎數基礎上增加對應數的一半 + coordinate <- c(coordinate,temp) + base <- base + test[i] ## 基礎數遞增 + } > coordinate ## 結果 [1] 10 45 90 140 210

2、shell實現

root@DESKTOP-1N42TVH:/home/test# ls
a.txt
root@DESKTOP
-1N42TVH:/home/test# cat a.txt 20 50 40 60 80 root@DESKTOP-1N42TVH:/home/test# base=0 root@DESKTOP-1N42TVH:/home/test# temp=0 root@DESKTOP-1N42TVH:/home/test# for i in `cat a.txt`; do let temp=$base+$i*1/2,base=$base+$i;echo $temp>> result.txt; done root@DESKTOP-1N42TVH:/home/test# ls a.txt result.txt root@DESKTOP
-1N42TVH:/home/test# cat result.txt ##檢視結果 10 45 90 140 210