R替换数据帧中的值

时间:2017-11-21 11:48:10

标签: r dataframe replace

我需要替换我的数据框中的一些数据,如下所示:

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

如果该单元格中有“*”,则将其替换为相同单元格FROM THE ROW ABOVE的值,并且仅在上面没有行的情况下,插入0。

预期结果:

  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 do I replace NA values with zeros in an R dataframe?的重复,因为我不想用NA替换每个出现的“*”,但我想用上面单元格中的值替换它(并且仅在第一个我希望将其替换为零) - 如果其他问题涵盖了这一点,我无法看到它,请举例说明知识渊博的人能够理解,谢谢

1 个答案:

答案 0 :(得分: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"