[R] searching and replacing in a data frame.

David Winsemius dwinsemius at comcast.net
Fri Jul 15 13:54:32 CEST 2011


On Jul 15, 2011, at 5:20 AM, Ashim Kapoor wrote:

> Dear R helpers,
>
>
> Please have a look at the following : -
>
> Note : My goal is to find and replace all Inf's in a data array with  
> 0.
>
>> t<-data.frame(A=c(Inf,0,0),B=c(1,2,3))
>> t
>    A B
> 1 Inf 1
> 2   0 2
> 3   0 3
>
>> str(t)
> 'data.frame':    3 obs. of  2 variables:
> $ A: num  Inf 0 0
> $ B: num  1 2 3
>> t[which(t==Inf,arr.ind=T)]
> [1] Inf

Several problems here.
`t` is a perfectly good function name so using it as an object name is  
confusing.


>> t[which(t==Inf,arr.ind=T)]<-0
> Error in `[<-.data.frame`(`*tmp*`, which(t == Inf, arr.ind = T),  
> value = 0)
> :
>  only logical matrix subscripts are allowed in replacement
>
> Query : Why does the search work but the replace not work ?

Because you gave a numeric matrix as an argument to "data.frame.[<-"  
and it wanted a different mode. I think it would have worked if `t`  
were a matrix.


>
> Many thanks for your time and efforts.

Two methods that would accomplish the task:

ttt<-data.frame(A=c(Inf,0,0),B=c(1,2,3))

ttt[is.infinite(as.matrix(ttt))] <- 0

Or:

apply(ttt, 1:2, function(x) x[is.infinite(x)] <- 0 )
>
> Ashim
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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
West Hartford, CT



More information about the R-help mailing list