Hi, A slight modification corrects this:
ttt <- data.frame(A = c(Inf, 0, 0), B = c(1, 2, 3)) apply(ttt, 2, function(x) {x[is.infinite(x)] <- 0; x}) and please do use spaces in your code. It is much more legible. Most notably spaces are after commas. Cheers, Josh On Sun, Jul 17, 2011 at 10:01 PM, Ashim Kapoor <ashimkap...@gmail.com> wrote: > Dear David, > > Many thanks for your reply. > > On Fri, Jul 15, 2011 at 5:24 PM, David Winsemius > <dwinsem...@comcast.net>wrote: > >> >> 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 ) >> >>> >>> >> ttt > A B > 1 Inf 1 > 2 0 2 > 3 0 3 >> apply(ttt,c(1,2),function(x) x[is.infinite(x)]<-0) > A B > [1,] 0 0 > [2,] 0 0 > [3,] 0 0 >> apply(ttt,c(1,2),function(x) x[is.infinite(x)]<-0) > A B > [1,] 0 0 > [2,] 0 0 > [3,] 0 0 > > Why do I have ALL zeroes ? well x is altered, but x is not what gets returned from apply. My alteration just makes it so x gets returned rather than the result of the subassignment. > > The other method DOES work. > > Thank you. > Ashim > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@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. > -- Joshua Wiley Ph.D. Student, Health Psychology University of California, Los Angeles https://joshuawiley.com/ ______________________________________________ R-help@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.