-1

I have a dataframe that looks like this:

Col1    Col2    Col3     Col4   Col5     Col6     Col7
  10       A       B        C     NA       NA       NA
  12       B       P        V      G       NA       NA
  14       C       I        K      H        M        H
  55       N       K       NA     NA       NA       NA
  34       M       N        O      P        Q       NA

How do I remove the last non-NA value in each row and replace with NA?

Final output:

Col1    Col2    Col3     Col4   Col5     Col6     Col7
  10       A       B       NA     NA       NA       NA
  12       B       P        V     NA       NA       NA
  14       C       I        K      H        M       NA
  55       N      NA       NA     NA       NA       NA
  34       M       N        O      P       NA       NA
nak5120
  • 4,089
  • 4
  • 35
  • 94

1 Answers1

4

We can use max.col to find the last non-NA element per row, then with row/column indexing, set those elements to NA in the original dataset

df1[cbind(1:nrow(df1), max.col(!is.na(df1), 'last'))] <- NA
df1
#   Col1 Col2 Col3 Col4 Col5 Col6 Col7
#1   10    A    B <NA> <NA> <NA> <NA>
#2   12    B    P    V <NA> <NA> <NA>
#3   14    C    I    K    H    M <NA>
#4   55    N <NA> <NA> <NA> <NA> <NA>
#5   34    M    N    O    P <NA> <NA>
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you @akrun. Btw this is all stemming from this question that I cannot figure out so I am trying to break it off piece by piece. http://stackoverflow.com/questions/43006044/match-dataframes-excluding-last-non-na-value-and-disregarding-order – nak5120 Mar 25 '17 at 14:36