[R] loop in function
Stephen Tucker
brown_emu at yahoo.com
Sun May 6 07:51:24 CEST 2007
Actually I am not sure what you want exactly, but is it
df1 <-data.frame(b=c(1,2,3,4,5,5,6,7,8,9,10))
df2 <-data.frame(x=c(1,2,3,4,5), y=c(2,5,4,6,5), z=c(10, 8, 7, 9, 3))
df1 <- cbind(df1,
"colnames<-"(sapply(with(df2,(x+y)/z),
function(a,b) a/b,b=df1$b),
paste("goal",seq(nrow(df2)),sep="")))
> round(df1,2)
b goal1 goal2 goal3 goal4 goal5
1 1 0.30 0.88 1.00 1.11 3.33
2 2 0.15 0.44 0.50 0.56 1.67
3 3 0.10 0.29 0.33 0.37 1.11
4 4 0.07 0.22 0.25 0.28 0.83
5 5 0.06 0.17 0.20 0.22 0.67
6 5 0.06 0.17 0.20 0.22 0.67
7 6 0.05 0.15 0.17 0.19 0.56
8 7 0.04 0.12 0.14 0.16 0.48
9 8 0.04 0.11 0.12 0.14 0.42
10 9 0.03 0.10 0.11 0.12 0.37
11 10 0.03 0.09 0.10 0.11 0.33
each column "goal" corresponds to row of df1. Alternatively, the sapply()
function can be rewritten with apply():
apply(df2,1,
function(a,b) (a["x"]+a["y"])/(a["z"]*b),
b=df1$b)
Hope this answered your question...
--- sumfleth at geographie.uni-kiel.de wrote:
> Dear Mailing-List,
> I think this is a newbie question. However, i would like to integrate a
> loop in the function below. So that the script calculates for each
> variable within the dataframe df1 the connecting data in df2. Actually it
> takes only the first row. I hope that's clear. My goal is to apply the
> function for each data in df1. Many thanks in advance. An example is as
> follows:
>
> df1 <-data.frame(b=c(1,2,3,4,5,5,6,7,8,9,10))
> df2 <-data.frame(x=c(1,2,3,4,5), y=c(2,5,4,6,5), z=c(10, 8, 7, 9, 3))
> attach(df2)
> myfun = function(yxz) (x + y)/(z * df1$b)
> df1$goal <- apply(df2, 1, myfun)
> df1$goal
>
> regards,
>
> kay
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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