[R] zero fill empty cell in data.frame

Kenn Konstabel lebatsnok at gmail.com
Tue Apr 19 13:08:47 CEST 2011


On Tue, Apr 19, 2011 at 1:45 PM, Rolf Turner <rolf.turner at xtra.co.nz> wrote:
> On 19/04/11 21:39, Simone Gabbriellini wrote:
>>
>> Hello List,
>>
>> I have a data frame like:
>>
>>        V130    V131    V132    V133    V134    V135    V136
>> 1       0               0               0.9             0
>> 0.9             0               0
>> 2       0               0               0                       0
>>       0               0.8
>> 3       0               0               0              0
>>  0.9             0               0
>> 4       0.9             0               0              0                0
>>               0               0.9
>> 5       0               0                               0
>>
>> 6       0               0               0               0.9             0
>>               0               0.9
>> 7       0               0               0.8             0              0
>>              0               0
>> 8       0.9             0                               0
>> 0.9             0.8             0
>> 9       0               0               0               0.9
>> 0.9             0               0
>> 10      0               0               0               0               0
>>               0               0.9
>>
>> I would like to fill the empty cells with a 0... how to address those
>> empty cells?

>From what the data frame looks like, you seem to have character values
or factors there.  (You could check it with sapply(DF, is) or just
look at the Nth column separately: DF[,1].) If you need numeric
values, you might want first convert them to numeric and then use
is.na, otherwise, Dimitris Rizopoulos has offered a very general
solution.


/.../    Rolf Turner wrote:
> In general, filling empty cells with zeros is ***very bad practice***.  Zero
> is not the same thing as ``missing''.   So basically:  Don't do this!  I
> don't care how badly you want to do it, or who told you to do it, just ***don't***.

But then again, consider that life, in general, is dangerous and ends
with death. I know at least one real example where replacing NA's with
zeros (with some caution) was just the right thing to do (respondents
had to check 5 items in a list of 20, and in data entry, checked items
were entered as 1's but the cells corresponding to unchecked items
were left empty ... so I had to replace all NA's with 0's except in
rows with nothing but NA's; there are probably many other legitimate
examples).

Best regards,

Kenn Konstabel



More information about the R-help mailing list