3

I need to replace some data in my dataframe, which looks like this:

  V1 V2 V3 V4
1  *  *  4  5
2  *  *  4  *
3  4  *  2  2
4  *  *  1  *

If a "*" is in that cell, replace it with the value of the same cell FROM THE ROW ABOVE, and ONLY if there is no row above, insert a 0.

expected result:

  V1 V2 V3 V4
1  0  0  4  5
2  0  0  4  5
3  4  0  2  2
4  4  0  1  2

How can I do this?

Edit: this is not a duplicate of How do I replace NA values with zeros in an R dataframe? since I dont want to replace every occurence of "*" with NA, but I want to replace it with the value from the cell above (and only in the first row I want to replace it by a zero) - in case this is covered by the other question, i cant see it, please give an example that somebody with very little r knowledge is able to understand, thanks

4
  • Just do zoo::na.locf(replace(df1, df1=="*", NA)) It is better to keep as NA, but if it is needed, it is easier to change it to 0
    – akrun
    Nov 21, 2017 at 11:48
  • @akrun How is this replacing with the value of the same cell from the row above? Seems like it replaces everything with 0. data[2,4] in the example given is to be replaced by 5, not by 0.
    – Bernhard
    Nov 21, 2017 at 11:50
  • @Bernhard You are right. I missed that part. Corrected
    – akrun
    Nov 21, 2017 at 11:51
  • 1
    Or with tidyverse df1 %>% mutate_all(funs(replace(., .=="*", NA))) %>% fill(names(.)) %>% mutate_all(funs(replace(., is.na(.), 0)))
    – akrun
    Nov 21, 2017 at 11:55

1 Answer 1

1
aa<-matrix(c("*","*","4","5","*","*","4","*","4","*","2","2","*","*","1","*"),ncol=4,byrow=T)

aa
   [,1] [,2] [,3] [,4]
[1,] "*"  "*"  "4"  "5" 
[2,] "*"  "*"  "4"  "*" 
[3,] "4"  "*"  "2"  "2" 
[4,] "*"  "*"  "1"  "*" 

aa[aa=="*"]=0
aa
     [,1] [,2] [,3] [,4]
[1,] "0"  "0"  "4"  "5" 
[2,] "0"  "0"  "4"  "0" 
[3,] "4"  "0"  "2"  "2" 
[4,] "0"  "0"  "1"  "0"

Not the answer you're looking for? Browse other questions tagged or ask your own question.