在我的数据框的一列中,我有一些空单元格。数据如下所示:
yymmdd lat lon mag depth knmilocatie baglocatie tijd
19861226 52.992 6.548 2.8 1.0 Assen Assen 74751
19871214 52.928 6.552 2.5 1.5 Hooghalen 204951
19891201 52.529 4.971 2.7 1.2 Purmerend Kwadijk 200914
19910215 52.771 6.914 2.2 3.0 Emmen Emmen 21116
19910425 52.952 6.575 2.6 3.0 Geelbroek Ekehaar 102631
19910808 52.965 6.573 2.7 3.0 Eleveld Assen 40114
期望的结果是:
yymmdd lat lon mag depth knmilocatie baglocatie tijd
19861226 52.992 6.548 2.8 1.0 Assen Assen 74751
19871214 52.928 6.552 2.5 1.5 Hooghalen Hooghalen 204951
19891201 52.529 4.971 2.7 1.2 Purmerend Kwadijk 200914
19910215 52.771 6.914 2.2 3.0 Emmen Emmen 21116
19910425 52.952 6.575 2.6 3.0 Geelbroek Ekehaar 102631
19910808 52.965 6.573 2.7 3.0 Eleveld Assen 40114
受到this solution的启发,我尝试用以下内容替换空单元格:
df$baglocatie[df$baglocatie == ""] <- df$knmilocatie
然而,这不起作用,因为空单元格填充了错误的值。 Another possible solution也没有用。
我该如何解决这个问题?
答案 0 :(得分:13)
尝试ifelse
:
df$baglocatie <- ifelse(df$baglocatie == "", df$knmilocatie, df$baglocatie)
答案 1 :(得分:4)
您还需要索引替换列:
df[ df$baglocatie == "", "baglocatie" ] <- df[ df$baglocatie == "", "knmilocatie" ]
答案 2 :(得分:1)
或者您可以使用支持向量:
empty <- df$baglocatie == ""
df$baglocatie[empty] <- df$knmilocatie[empty]