Re: [R] vectorization of loops in R

2021-11-18 Thread PIKAL Petr
Hi above tapply and aggregate, split *apply could be used) sapply(with(df, split(z, y)), mean) Cheers Petr > -Original Message- > From: R-help On Behalf Of Luigi Marongiu > Sent: Wednesday, November 17, 2021 2:21 PM > To: r-help > Subject: [R] vectorization of loops

Re: [R] vectorization of loops in R

2021-11-17 Thread Jan van der Laan
Have a look at the base functions tapply and aggregate. For example see: - https://cran.r-project.org/doc/manuals/r-release/R-intro.html#The-function-tapply_0028_0029-and-ragged-arrays , - https://online.stat.psu.edu/stat484/lesson/9/9.2, - or ?tapply and ?aggregate. Also your current code

Re: [R] vectorization of loops in R

2021-11-17 Thread Kevin Thorpe
If I follow what you are trying to do, you want the mean of z for each value of y. tapply(df$z, df$y, mean) > On Nov 17, 2021, at 8:20 AM, Luigi Marongiu wrote: > > Hello, > I have a dataframe with 3 variables. I want to loop through it to get > the mean value of the variable `z`, as

[R] vectorization of loops in R

2021-11-17 Thread Luigi Marongiu
Hello, I have a dataframe with 3 variables. I want to loop through it to get the mean value of the variable `z`, as follows: ``` df = data.frame(x = c(rep(1,5), rep(2,5), rep(3,5)), y = rep(letters[1:5],3), z = rnorm(15), stringsAsFactors = FALSE) m = vector() for (i in unique(df$y)) { s = df[df$y