R replace values in dataframe

Viewed 2423

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

1 Answers
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"
Related