2

I have a dataframe called AD with 50 rows and 12 columns I'd like to add values by row, in order to have:

AD[1,2] <- AD[1,1] + AD[1,2]
AD[1,3] <- AD[1,2] + AD[1,3]

and so on for each row.

I tried the following:

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

Here an example:

    a  b  c
1   1  2  3
2   2  3  4
3   3  0  5
4   4  5  6
5   5  0  7
6   6  7  8

And I'd like to have:

    a  b  c
1   1  3  6
2   2  5  9
3   3  3  8
4   4  9  15
5   5  5  12
6   6  13 21
zx8754
  • 52,746
  • 12
  • 114
  • 209
jeff
  • 323
  • 1
  • 7
  • Sabrina, could you provide a numerical example for me to understand what you are looking for ? – Carles Jul 09 '19 at 10:40
  • @SabrinaG. - use the 'edit' link above and add the dataset (and ideally expected output) to the question. It won't format nicely in the comments unfortunately. – thelatemail Jul 09 '19 at 10:53
  • Where may I find the duplicated question? Thanks – jeff Jul 09 '19 at 11:13

1 Answers1

0

Do it as following: :)

> AD <-data.frame(a = c(1:6),
+            b = c(2,3,0,5,0,7),
+            c=  c(3:8))
> for(i in 1:nrow(AD)){
+   AD[i,2] <- AD[i,1] + AD[i,2]
+   AD[i,3] <- AD[i,2] + AD[i,3]
+   
+ }
> AD
  a  b  c
1 1  3  6
2 2  5  9
3 3  3  8
4 4  9 15
5 5  5 12
6 6 13 21
Carles
  • 2,731
  • 14
  • 25
  • 1
    Isn't the question summing across columns in each row though? – thelatemail Jul 09 '19 at 10:26
  • I understand the question as in my example ( I reedited the answer). @thelatemail, please tell me if I have understood it wrong. – Carles Jul 09 '19 at 10:29
  • It's probably easier to give an example - try `AD <- myframe` then run the two lines OP suggested. `AD[1,2] <- AD[1,1] + AD[1,2]` is overwriting the second column of the first row, with the sum of the first and second columns in the same row. – thelatemail Jul 09 '19 at 10:31
  • I agree partially. I have chanded the variable name. However, rewriting the same variables makes him/her not seeing what he is doing, therefore, I am writing it in different columns. – Carles Jul 09 '19 at 10:39
  • I can't just use cumsum because i don't need one cumulative sum for each row but a cumulative sum for each step (from AD[1,1] to AD[1,2] and so on). – jeff Jul 09 '19 at 11:07
  • I reedited it, so that now it should work in your way :) – Carles Jul 09 '19 at 11:13