[R] DataFrame help

Don MacQueen macq at llnl.gov
Thu Jul 16 23:34:14 CEST 2009


As others noted, you can use the built in function colSums, but you 
said you're writing your own. Given what you've got so far, that 
makes the issue one of structuring the output.

Try

csum <- function(m)
{
	a = data.frame(m)
	s = lapply(a,sum)
	unlist(s)
}

lapply() returns a list, so you have to use unlist() on it in order 
to restructure the list into a vector.


However:

Converting the matrix to a dataframe is not needed; you can use the 
apply() function on the matrix, as suggested by Jorge, in which case 
the result will already be a vector, so you won't need to unlist(). 
Then it's much simpler:

csum <- function(m) apply(m,2,sum)

A couple of other notes:

Using return() is unnecessary in such a simple function.

Be careful with terminology. You said you want the result as a single 
"list". But a list, in R, is an object with a particular structure, 
but *not* the structure you appear to be looking for, since your 
description "[1] 6 15 24" looks like a vector, not a list.

-Don


At 11:25 AM -0700 7/16/09, voidobscura wrote:
>Alright, so I am trying to write my own function to calculate column sums in
>a matrix.  I want the result as a single list with the values.
>
>So far I have:
>
>csum<-function(m)
>{
>	a = data.frame(m)
>	s = lapply(a,sum)
>	return(s)
>}
>
>What is the easiest way to have it return in a format such as [1] 6 15 24 ?
>
>Thanks.
>--
>View this message in context: 
>http://*www.*nabble.com/DataFrame-help-tp24521881p24521881.html
>Sent from the R help mailing list archive at Nabble.com.
>
>______________________________________________
>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.


-- 
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062




More information about the R-help mailing list