[英]How to loop through a dataset subtracting the value in the row below - Using R
I need help with the below question in R language. 我需要以下有关R语言问题的帮助。
Lets say I have a data set: 可以说我有一个数据集:
X Y
1 1
2 2
3 3
4 4
How would I go about looping through the dataset subtracting the X value in the current row from the X value in the row below, then going to the second row etc? 我将如何遍历数据集,从下一行的X值中减去当前行的X值,然后转到第二行等?
Currently I have the below: 目前,我有以下内容:
df <- (df[row(df)-1,1] - df[row(df)+1,1])
I would like to get the following: 我想得到以下内容:
X
-1
-1
-1
N/a
However it seems to being doing the calculations twice and I am getting? 但是,似乎要进行两次计算,我得到了吗?
X
-1
-1
-1
N/a
-1
-1
-1
N/a
I cant figure out why, any help would be appreciated? 我不知道为什么,任何帮助将不胜感激?
As @Sotos pointed out, you can solve this with diff
. 正如@Sotos指出的那样,您可以使用diff
解决此问题。
But the reason this isn't working is because row()
returns row numbers for both columns 但这不起作用的原因是因为row()
返回两列的行号
> row(df)
[,1] [,2]
[1,] 1 1
[2,] 2 2
[3,] 3 3
[4,] 4 4
If you select either column alone your code works: 如果仅选择任一列,则代码有效:
df <- (df[row(df)[,1]-1,1] - df[row(df)[,1]+1,1])
You could use diff()
. 您可以使用diff()
。 Also you could do it using a matrix multiplication approach. 您也可以使用矩阵相乘的方法。
Example 例
set.seed(42)
x <- sample(10, 10, replace=TRUE)
> x
[1] 10 10 3 9 7 6 8 2 7 8
> diff(x)
[1] 0 -7 6 -2 -1 2 -6 5 1
# difference matrix approach
lbd <- matrix(0, nrow=length(x) - 1, ncol=length(x)) # setup lambda
diag(lbd) <- -1
diag(lbd[, -1]) <- 1
> lbd
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] -1 1 0 0 0 0 0 0 0 0
[2,] 0 -1 1 0 0 0 0 0 0 0
[3,] 0 0 -1 1 0 0 0 0 0 0
[4,] 0 0 0 -1 1 0 0 0 0 0
[5,] 0 0 0 0 -1 1 0 0 0 0
[6,] 0 0 0 0 0 -1 1 0 0 0
[7,] 0 0 0 0 0 0 -1 1 0 0
[8,] 0 0 0 0 0 0 0 -1 1 0
[9,] 0 0 0 0 0 0 0 0 -1 1
> lbd %*% x # matrix multiplication, same result as in `diff(x)` above
[,1]
[1,] 0
[2,] -7
[3,] 6
[4,] -2
[5,] -1
[6,] 2
[7,] -6
[8,] 5
[9,] 1
Using your data: 使用数据:
x1 <- 1:4
lbd1 <- matrix(0, nrow=length(x1) - 1, ncol=length(x1))
diag(lbd1) <- -1
diag(lbd1[, -1]) <- 1
> lbd1 %*% x1
[,1]
[1,] 1
[2,] 1
[3,] 1
> diff(x1) # same
[1] 1 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.