Reputation: 79
I am very new to R and I'm trying to operate on each element of a data frame that looks like this:
> head(data)
V1 V2 V3 V4 V5 V6 V7 V8 V9
1 3.55271e-15 10.7349 21.9238 26.5136 42.38290 37.0355 28.6789 36.6033 26.46900
2 0.00000e+00 14.5497 19.4960 23.9728 37.66170 32.5874 32.9722 46.7856 41.23690
3 0.00000e+00 19.8794 12.6273 15.7562 26.07470 16.3857 33.3016 40.0800 33.45120
4 0.00000e+00 13.9638 33.8372 50.1383 52.74920 55.9552 79.8752 78.2309 76.51520
5 0.00000e+00 25.1614 23.7001 21.1502 7.11349 13.3939 18.4262 1.1183 8.78106
6 3.55271e-15 11.1300 10.5257 21.4103 8.95956 14.8252 42.4594 40.8457 29.57740
What I want to do is apply a function to each element in the data frame then average the results for each k:
for (k in c(1,100){
sample <- cos(k*data)
average <- mean(sample)}
But I realize that this will overwrite the sample variable and I will just be left with one sample (at k = 100).
I also know that R prefers vectorized functions rather than for loops, so how should I approach this problem? Thanks!
Upvotes: 3
Views: 47
Reputation: 1975
You could use sapply() to apply your function to your data and return the average.
sapply(1:100, (function(i){
sample <- cos(i*data)
mean(sample)
}))
Alternatively, if you want to store your "samples" in a list, you could use lapply() first and then sapply() again on your samples list.
samples <- lapply(1:100, (function(i){
cos(i*data)
}))
averages <- sapply(samples, mean)
head(averages)
[1] 0.046893344 0.032709183 -0.009479597 -0.185085895 -0.395590101 0.554012071
Upvotes: 1