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

 

posted @ 2022-01-06 11:51  小鲨鱼2018  阅读(100)  评论(0编辑  收藏  举报