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 @   小鲨鱼2018  阅读(105)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2021-01-06 c语言中for循环结构
2021-01-06 c语言中while循环步长大于2不存在后置运算??
2021-01-06 c语言中统计正整数的位数
点击右上角即可分享
微信分享提示