Hello, What is the best way to turn a matrix into a list removing NaN's? I'm new to R... Start:> mt = matrix(c(1,4,NaN,5,3,6),2,3) > mt[,1] [,2] [,3] [1,] 1 NaN 3 [2,] 4 5 6 Desired result:> lst[[1]] [1] 1 3 [[2]] [1] 4 5 6 Thanks! Ben [[alternative HTML version deleted]]
R. Michael Weylandt
2011-Sep-27 20:07 UTC
[R] remove NaN from element in a vector in a list
Try this: alply(mt, 1, function(x) as.numeric(na.omit(x))) The as.numeric() addition may be necessary to strip the extra attributes na.omit() wants to add. Michael On Tue, Sep 27, 2011 at 4:02 PM, Ben qant <ccquant@gmail.com> wrote:> Hello, > > What is the best way to turn a matrix into a list removing NaN's? I'm new > to > R... > > Start: > > > mt = matrix(c(1,4,NaN,5,3,6),2,3) > > mt > [,1] [,2] [,3] > [1,] 1 NaN 3 > [2,] 4 5 6 > > Desired result: > > > lst > [[1]] > [1] 1 3 > > [[2]] > [1] 4 5 6 > > > Thanks! > > Ben > > [[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. >[[alternative HTML version deleted]]
On Sep 27, 2011, at 4:02 PM, Ben qant wrote:> Hello, > > What is the best way to turn a matrix into a list removing NaN's? > I'm new to > R... > > Start: > >> mt = matrix(c(1,4,NaN,5,3,6),2,3) >> mt > [,1] [,2] [,3] > [1,] 1 NaN 3 > [2,] 4 5 6> apply(mt, 1, function(x) x[!is.nan(x)] ) [[1]] [1] 1 3 [[2]] [1] 4 5 6 The function is.finite would also remove infinities as well as the NaNs.> > Desired result: > >> lst > [[1]] > [1] 1 3 > > [[2]] > [1] 4 5 6 > > > Thanks! >David Winsemius, MD West Hartford, CT
>> apply(mt, 1, function(x) x[!is.nan(x)] ) > [[1]] > [1] 1 3 > > [[2]] > [1] 4 5 6You need to be a little careful with apply:> mt2 <- matrix(c(1,4,2,5,3,6),2,3) > apply(mt2, 1, function(x) x[!is.nan(x)] )[,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 Depending on the input you will get a list or matrix as output. Hadley -- Assistant Professor / Dobelman Family Junior Chair Department of Statistics / Rice University http://had.co.nz/