1

Suppose I have a sample data.frame as follows:

1  2  3  4  5  6  7  8  9  11
2  3  4  5  6  7  8  9  10  12
3  4  5  6  7  8  9  10  11  13

I want to subtract each column from its next column in my data.frame, so I get something like this:

1  1  1  1  1  1  1  1  2  
1  1  1  1  1  1  1  1  2  
1  1  1  1  1  1  1  1  2  

My real sample has 2291 rows and 50 columns, the code I wrote looks something like this:

delta <- data.frame(matrix(NA, nrow = 2291, ncol = 49 )) 
for(i in 1:nrow(df)){
for(j in 1:ncol(df)-1){
delta[i,j] <- df[i,j+1]-df[i,j] 
}
}

But I get the following error message:

Error in data.frame(value, row.names = rn, check.names = FALSE, check.rows = FALSE) : 'row.names' should specify one of the variables

What am I doing wrong? What is the best way to do this?

Sotos
  • 51,121
  • 6
  • 32
  • 66
rishi
  • 267
  • 1
  • 9

1 Answers1

7

We can remove the first and last columns and do a subtraction

df[-1] - df[-ncol(df)]
#   v2 v3 v4 v5 v6 v7 v8 v9 v10
#1  1  1  1  1  1  1  1  1   2
#2  1  1  1  1  1  1  1  1   2
#3  1  1  1  1  1  1  1  1   2
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Jesus this was so easy, thanks. What does `df[-ncol(df)]` mean? – rishi May 18 '18 at 12:46
  • 1
    @rishi It removes the last column `ncol`- extract the last column and by doing `-`, removes that column. Similarly, `df[-1]` removes the first column. So, basically, you have two subsets of datasets that have the same length, but it starts from 1 and 2nd column – akrun May 18 '18 at 12:48
  • aah that makes sense, thanks! Btw do you know why didn't my for loops work? I know looking at other people's codes is difficult but do you know the reasons for my warnings? – rishi May 18 '18 at 12:51
  • 1
    @rishi You are doing a nested loop, which is not necessary. 2nd is that `1:ncol(df)-1` and `1:(ncol(df)-1` are different – akrun May 18 '18 at 12:53