Prad
Prad

Reputation: 339

n number of column wise subtraction

need help in N number or column wise subtraction, Below are the columns in a input dataframe.

input dataframe:

A   B   C   D
1   4   6   2
3   3   3   4
1   2   2   2
4   4   4   4
5   2   3   2

Expected Output:

A      B-A     C-B      D-C
1       3       2       -4
3       0       0       1
1       1       0       0
4       0       0       0
5       -3      1       -1

similarly there will be many column upto 10.

i am able to write the code for 2 columns:

Code:

df$(B-A) <- df$B - df$A
df$(C-B) <- df$C - df$B

and so on... but in this should come in loop as there are almost 10 to 12 columns. Please help me.

Upvotes: 3

Views: 100

Answers (3)

Erdogan CEVHER
Erdogan CEVHER

Reputation: 1609

Here is the instructive/pedagogic straightforward solution:

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

Get the pattern:

cbind(df[1], df[2] - df[1], df[3] - df[2], df[4] - df[3]) # solved

Now, use dynamic programming in R to finish (in the general case):

cbind(df[1], sapply(1:(ncol(df)-1), function(i) df[i+1] - df[i]))

Output:

  A  B C  D
1 1  3 2 -4
2 3  0 0  1
3 1  1 0  0
4 4  0 0  0
5 5 -3 1 -1

Upvotes: 1

nghauran
nghauran

Reputation: 6768

Using apply() you can also try this

cbind(df[1], t(apply(df, 1, diff)))

Output:

  A  B C  D
1 1  3 2 -4
2 3  0 0  1
3 1  1 0  0
4 4  0 0  0
5 5 -3 1 -1

Upvotes: 1

Sotos
Sotos

Reputation: 51592

Here is a Vectorized way to do this,

cbind.data.frame(df[1], df[-1] - df[-ncol(df)])

which gives,

  A  B C  D
1 1  3 2 -4
2 3  0 0  1
3 1  1 0  0
4 4  0 0  0
5 5 -3 1 -1

Upvotes: 5

Related Questions