[R] Replace NAs in a range of data frame columns

David Winsemius dwinsemius at comcast.net
Sun Dec 13 01:14:06 CET 2009


On Dec 12, 2009, at 6:15 PM, Patrizio Frederic wrote:

> hi Michael,
> the following code should work
>
> b <- a[match('first',names(a)): match('last',names(a))]
> b[is.na(b)]<-0

This might not throw an error:

b <- apply(a[match('first',names(a)): match('last',names(a))], 1:2,
                      function(x) ifelse(is.na(x), 0, x) )

> a[match('first',names(a)): match('last',names(a))] <- b

And this might actually replace a range of columns:

a[ , match('first',names(a)): match('last',names(a))] <- b

more cheer;
David

>
> cheers,
>
> Patrizio
>
> 2009/12/13 Michael Scharkow <michael at underused.org>:
>> Dear all,
>>
>> I'm stuck in a seemingly trivial task that I need to perform for many
>> datasets. Basically, I want to replace NA with 0 in a specified  
>> range of
>> columns in a dataframe. I know the first and last column to be  
>> recoded only
>> by its name.
>>
>> I can select the columns starting like this
>> a[match('first',names(a)): match('last',names(a))]
>>
>> The question is how can replace all NA with 0 in this subset of the  
>> data?
>>
>> Thanks and greetings,
>> Michael
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>
>
> -- 
> +-------------------------------------------------
> | Patrizio Frederic, PhD
> | Assistant Professor,
> | Department of Economics,
> | University of Modena and Reggio Emilia,
> | Via Berengario 51,
> | 41100 Modena, Italy
> |
> | tel:  +39 059 205 6727
> | fax:  +39 059 205 6947
> | mail: patrizio.frederic at unimore.it
> +-------------------------------------------------
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list