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

Patrizio Frederic frederic.patrizio at gmail.com
Sun Dec 13 00:15:01 CET 2009


hi Michael,
the following code should work

b <- a[match('first',names(a)): match('last',names(a))]
b[is.na(b)]<-0
a[match('first',names(a)): match('last',names(a))] <- b

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
+-------------------------------------------------




More information about the R-help mailing list