[R] How to perform a calculation in each element of my list?

Daniel Malter daniel at umd.edu
Thu Jul 23 20:21:44 CEST 2009


Hi Mark, study the following example. The two simulated dataframes are put
in a list called listdata. The loop iterates throught the elements in the
list and multiplies the last column "listdata[[i]][,length(listdata[[i]])]"
by the column before the last "listdata[[i]][,length(listdata[[i]])-1]".
This new columns is assigned to be the new column after the last of the
respective dataframe in the list "listdata[[i]][,length(listdata[[i]])+1]"

x1=rnorm(100,0,1)
x2=rnorm(100,0,1)
x3=rnorm(100,0,1)
x4=rnorm(100,0,1)

data1=data.frame(x1,x2)
data2=data.frame(x3,x4)

listdata=list(data1,data2)

for(i in 1:length(listdata)){
 
listdata[[i]][,length(listdata[[i]])+1]=listdata[[i]][,length(listdata[[i]])
]*listdata[[i]][,length(listdata[[i]])-1]
  }

HTH,
Daniel 


-------------------------
cuncta stricte discussurus
-------------------------

-----Ursprüngliche Nachricht-----
Von: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] Im
Auftrag von Mark Na
Gesendet: Thursday, July 23, 2009 2:06 PM
An: r-help at r-project.org
Betreff: [R] How to perform a calculation in each element of my list?

Hi R-helpers,

I have a list containing 10 elements, each of which is a dataframe. I wish
to add a new column to each list element (dataframe) containing the product
of the last two columns of each dataframe.

I'd appreciate any pointers, thanks!

Mark Na

	[[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.




More information about the R-help mailing list