Calculation in Dataframe keeping first row as reference

r dataframe matrix data.table apply

64 观看

3回复

121 作者的声誉

My first row is the reference value for addition of the below rows, for N number of columns.

Data

A   B   C   D
3   5   1   2

1   4   5   3
2   2   2   4
3   1   3   1
4   3   1   2

Calculation as follows:

  • 3, is reference value that is added, which is 3 should be added to 1, 2, 3, and 4, similarly 5 is the reference value that is - added to 4,2,1,3 and then 1 is reference value added to 5,2,3,1 and so .... till n columns.

    1 + 3   4 + 5   5 + 1   3 + 2
    2 + 3   2 + 5   2 + 1   4 + 2
    3 + 3   1 + 5   3 + 1   1 + 2
    4 + 3   3 + 5   1 + 1   2 + 2
    

Expected output:

A   B   C   D
4   9   6   5
5   7   3   6
6   6   4   3
7   8   2   4

Please help. Thanks.

作者: Prad 的来源 发布者: 2017 年 12 月 27 日

回应 3


5

159429 作者的声誉

决定

Maybe just this:

c(mydf[1, ]) + mydf[-1, ]
##   A B C D
## 2 4 9 6 5
## 3 5 7 3 6
## 4 6 6 4 3
## 5 7 8 2 4

Starting data.frame:

mydf <- structure(list(A = c(3L, 1L, 2L, 3L, 4L), B = c(5L, 4L, 2L, 1L, 
    3L), C = c(1L, 5L, 2L, 3L, 1L), D = c(2L, 3L, 4L, 1L, 2L)), .Names = c("A", 
    "B", "C", "D"), row.names = c(NA, 5L), class = "data.frame")
作者: A5C1D2H2I1M1N2O1R2T1 发布者: 2017 年 12 月 27 日

2

474039 作者的声誉

We can do

(df1[1,][col(df1)] + df1)[-1,]
#  A B C D
#2 4 9 6 5
#3 5 7 3 6
#4 6 6 4 3
#5 7 8 2 4
作者: akrun 发布者: 2017 年 12 月 27 日

0

11 作者的声誉

If you are trying to replace the values in your initial dataframe with the new values, you could do the following:

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

for (i in 2:nrow(df)) {
  for (j in 1:ncol(df)) {
    df[i,j] <- df[1,j] + df[i,j] 
  }
}

This could probably be vectorized and run faster which would be helpful if you have a very large dataframe, but it will work if you need a quick and dirty solution.

Output:

  A B C D
1 3 5 1 2
2 4 9 6 5
3 5 7 3 6
4 6 6 4 3
5 7 8 2 4

Hope this is helpful!

作者: Ironman454 发布者: 2017 年 12 月 27 日
32x32