[R] Replacing NAs with 0 for variables with the same ending

Henrique Dallazuanna wwwhsd at gmail.com
Fri Jan 15 14:30:39 CET 2010


In grep use: grep("x$", names(data)).

'$' matchs 'x' in the end of string

On Fri, Jan 15, 2010 at 11:14 AM, Uli Kleinwechter
<u.kleinwechter at uni-hohenheim.de> wrote:
> Jim Lemon schrieb:
>> On 01/15/2010 07:10 PM, Uli Kleinwechter wrote:
>>> Dear all,
>>>
>>> I'm looking for a way to replace NA's with 0 for a number of variables
>>> which share the same ending and which constitute a subset of a data
>>> frame.
>>>
>>> Say, for example, there is
>>>
>>>> data<- data.frame(ax=c(1,2,3,NA,0) , bx=c(3,5,NA,5,1) ,
>>> ay=c(5,NA,2,NA,0) , by=c(4,2,NA,2,1))
>>>> data
>>>    ax bx ay by
>>> 1  1  3  5  4
>>> 2  2  5 NA  2
>>> 3  3 NA  2 NA
>>> 4 NA  5 NA  2
>>> 5  0  1  0  1
>>>
>>> I wish to apply something like  //
>>> //
>>> />  data[is.na(data)]<- 0/
>>> //
>>> but not to the entire data frame, rather only to the variables ending
>>> with x.
>>>
>> Hi Uli,
>> How about:
>>
>> data[,grep("x",names(data))][is.na(data[,grep("x",names(data))])]<-0
>>
>> Jim
>>
> Hi Jim,
>
> thanks a lot. I'm just afraid that grep matches any occurence of "x" in
> the variable name. So variables which would contain "x" at any position,
> not necessarily only at the last one would be selected, as well. To
> refine my example (sorry for having been so imprecise before...):
>
>> data<- data.frame(ax=c(1,2,3,NA,0) , bx=c(3,5,NA,5,1)
> ,ay=c(5,NA,2,NA,0) , xy=c(4,2,NA,2,1))
>> data
>  ax bx ay xy
> 1  1  3  5  4
> 2  2  5 NA  2
> 3  3 NA  2 NA
> 4 NA  5 NA  2
> 5  0  1  0  1
>
> The task, again, would be to replace NA's with 0 in "ax" and "bx", but
> not in "ay" and "xy"
>
> Best,
>
> Uli
>
> ______________________________________________
> 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.
>



-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O



More information about the R-help mailing list