Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace empty values with value from other column in a dataframe

In one column of my dataframe I have some empty cells. The data looks like this:

   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

The desired result is:

   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

Inspired by this solution, I tried to replace the empty cells with:

df$baglocatie[df$baglocatie == ""] <- df$knmilocatie

However, this did not work as the empty cells were filled with the wrong values. Another possible solution also didn't work.

How do I solve this?

like image 558
Jaap Avatar asked Jan 17 '14 09:01

Jaap


3 Answers

Try ifelse:

df$baglocatie <- ifelse(df$baglocatie == "", df$knmilocatie, df$baglocatie)
like image 65
zx8754 Avatar answered Nov 10 '22 13:11

zx8754


You need to index also the replacing column:

df[ df$baglocatie == "", "baglocatie"  ]  <- df[ df$baglocatie == "", "knmilocatie" ]
like image 27
Beasterfield Avatar answered Nov 10 '22 12:11

Beasterfield


Or you can use a support vector:

empty <- df$baglocatie == ""
df$baglocatie[empty] <- df$knmilocatie[empty]
like image 34
LuigiZ Avatar answered Nov 10 '22 11:11

LuigiZ