0

My sample data looks like this

 DF
n    a   b    c    d
1    NA  NA   NA   NA
2    1    2    3    4
3    5    6    7    8
4    9    NA   11   12
5    NA   NA   NA   NA
6    4    5     6    NA
7    8    9     10   11
8    12   13    15   16
9    NA   NA    NA   NA

I need to substract row 2 from row 3 and row 4.

Similarly i need to subtract row 6 from row 7 and row 8

My real data is huge, is there a way of doing it automatically. It seems it could be some for loop but as I am dummy R user my trials were not successful. Thank you for any help and tips.

UPDATE

I want to achieve something like this

DF2
rowN1<-DF$row3-DF$row2
rowN2<-DF$row4-DF$row2

rowN3<-DF$row7-DF$row6 # there is NA in row 6 so after subtracting there should be NA also
rowN4<-DF$row8-DF$row6
HoHoHo
  • 65
  • 1
  • 10
  • Are you trying to skip rows that are all `NA`, or contain *any* `NA` values? Because rows 4 and 6 have a single `NA` in them. Please demonstrate what your desired output is. – nrussell Mar 09 '16 at 14:22
  • Thank you for the comment.I will update now the question. – HoHoHo Mar 09 '16 at 14:24
  • The question seems a duplicate of https://stackoverflow.com/questions/35781173/within-group-differences-from-group-member and https://stackoverflow.com/questions/35892111/subtract-one-row-from-another-row-in-df, except this one has some NAs in it. What's with all these duplicates of difference in rows? I didn't even try searching, but I'd bet there are more, since 2 of these are from today alone and the other from just last week. – shea Mar 09 '16 at 14:38
  • One of them was mine. but the data was wrong as i didn't specify sample data correctly. Others i don't know what are the questions, sorry – HoHoHo Mar 09 '16 at 14:51

1 Answers1

0

Here's one idea

set.seed(1)
(m <- matrix(sample(c(1:9, NA), 60, T), ncol=5))
#       [,1] [,2] [,3] [,4] [,5]
#  [1,]    3    7    3    8    8
#  [2,]    4    4    4    2    7
#  [3,]    6    8    1    8    5
#  [4,]   NA    5    4    5    9
#  [5,]    3    8    9    9    5
#  [6,]    9   NA    4    7    3
#  [7,]   NA    4    5    8    1
#  [8,]    7    8    6    6    1
#  [9,]    7   NA    5    6    4
# [10,]    1    3    2    8    6
# [11,]    3    7    9    1    7
# [12,]    2    2    7    5    5

idx <- seq(2, nrow(m)-2, 4)
do.call(rbind, lapply(idx, function(x) {
  rbind(m[x+1, ]-m[x, ], m[x+2, ]-m[x, ])
}))
# [1,]    2    4   -3    6   -2
# [2,]   NA    1    0    3    2
# [3,]   NA   NA    1    1   -2
# [4,]   -2   NA    2   -1   -2
# [5,]    2    4    7   -7    1
# [6,]    1   -1    5   -3   -1
lukeA
  • 53,097
  • 5
  • 97
  • 100