如何在R中的每两连续行中找到值的差异? [英] How to find the difference in value in every two consecutive rows in R?

查看:76
本文介绍了如何在R中的每两连续行中找到值的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个总共 969 行的大表,我需要找出每两行之间的差异,例如row1 和 row2、row2 和 row3、row3 和 row4 等.我该怎么做?命令 diff() 告诉我这样做,但我不知道从哪里开始.

I have a big table of total 969 rows and I need to find the difference between every two rows, e.g. row1 and row2, row2 and row3, row3 and row4 etc. How can I do that? I was told to do it by the command diff() but I have no idea where to start.

推荐答案

以下是如何在内置的 mtcars 上使用 diff() 的示例 数据框.您必须选择一列来执行差异:

Here's an example of how to use diff() on the built-in mtcars data.frame. You have to select a column to perform the diff over:

mtcars
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
[..snip..]
Ford Pantera L      15.8   8 351.0 264 4.22 3.170 14.50  0  1    5    4
Ferrari Dino        19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1    5    8
Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1    4    2

计算例如的连续差异列qsec":

Calculate the successive differences of e.g. the column "qsec":

diff(mtcars$qsec)
 [1]  0.56  1.59  0.83 -2.42  3.20 -4.38  4.16  2.90 -4.60  0.60 -1.50  0.20
[13]  0.40 -0.02 -0.16 -0.40  2.05 -0.95  1.38  0.11 -3.14  0.43 -1.89  1.64
[25]  1.85 -2.20  0.20 -2.40  1.00 -0.90  4.00

这篇关于如何在R中的每两连续行中找到值的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆