The following is sample data and part of function I have trouble with.
# data
Gr1 <- data.frame (group = rep(1:2, each = 2001),
position = round (c(0, cumsum (rnorm (2000, 0.05, 0.08)), 0,
cumsum (rnorm (2000, 0.05, 0.08)))))
Gr2 <- data.frame (group = rep(1:2, each = 2001),
position = round (c(0, cumsum (rnorm (2000, 0.05, 0.08)), 0,
cumsum (rnorm (2000, 0.04, 0.08)))))
Gr3 <- data.frame (group = rep(1:2, each = 2001),
position = round (c(0, cumsum (rnorm (2000, 0.05, 0.08)), 0,
cumsum (rnorm (2000, 0.05, 0.08)))))
groupobs = list(Gr1, Gr2, Gr3)
grnames = c("A", "B", "C")
spacing = c(0, 0.1, 0.3)
# for loop
for (i in 1:length(groupobs)){
groupobs[i]$sgrp <- grnames[i]
groupobs[i]$y <- groupobs[i]$group + spacing[i]
}
# binding of list components
mydf <- data.frame (rbind (groupobs)
How can I achieve this ?
Edit: With above loop, I want to achieve the following manual process. I want to automate n number of dataframe, so that I do not need to write a lengthy steps:
Please note that each of dataframes in this have same name of variables. For each component dataframe I want perform the following tasks. If I do it without looping:
# for first dataframe with in list
Gr1$sgrp <- grnames[1]
Gr1$y <- Gr1$group + spacing[1]
# for second dataframe in the list
Gr2$sgrp <- grnames[2]
Gr2$y <- Gr1$group + spacing[2]
# for third dataframe in the list
Gr3$sgrp <- grnames[3]
Gr3$y <- Gr1$group + spacing[3]
mydf <- data.frame (rbind (Gr1, Gr2, Gr3))
I maybe be way off here but
might be what you are after………….
EDIT: changed to hopefully produce dataframe
thanks to @jon