bwi321
bwi321

Reputation: 123

Subtracting columns in a loop

I've got a data frame like that:

df:
   A  B  C
1  1  2  3
2  2  2  4
3  2  2  3

I would like to subtract each column with the next smaler one (A-0, B-A, C-B). So my results should look like that:

df:
   A  B  C
1  1  1  1
2  2  0  2
3  2  0  1

I tried the following loop, but it didn't work.

for (i in 1:3) {
  j <- data[,i+1] - data[,i]
}

Upvotes: 3

Views: 467

Answers (2)

akrun
akrun

Reputation: 887148

We can also remove the first and last column and do the subtraction

df[-1] <- df[-1]-df[-length(df)]

data

df <- data.frame(A = c(1, 2, 2), B = c(2, 2, 2), C = c(3, 4, 3))

Upvotes: 0

Darren Tsai
Darren Tsai

Reputation: 35554

Try this

df - cbind(0, df[-ncol(df)])

#   A B C
# 1 1 1 1
# 2 2 0 2
# 3 2 0 1

Data

df <- data.frame(A = c(1, 2, 2), B = c(2, 2, 2), C = c(3, 4, 3))

Upvotes: 1

Related Questions