Closed willpearse closed 8 years ago
I think you've deleted this comment (?) but I can solve your problem anyway.
You're not quite getting how apply works - consider apply to be a replacement for a loop. If you're using apply, or essentially any of the functions I taught you yesterday, you don't need to use a loop!
To see what I mean, focus on your first version, as that's the closest and the most idiomatic I think. Actually type apply(x, 2, sum) into your R console. What do you get? You get the sum of each column! So there's no need to loop over the columns - you've already got the information you need! So something like:
sum.output[,1] <- apply(x, 2, sum)
... would give you what you need! Does that make sense?
On Mon, 31 Oct 2016 at 19:33 mahagadorn notifications@github.com wrote:
Hi Will,
Thanks for all of your help today. Alas, I am still not understanding something.
I wrote a simple summary function (lesson 4.2) that I am just trying to get to work. For simplicity, I only have it doing one function until I figure out how to fix my issue. I am trying to get it to save as a data.matrix again, and I think it is the same issue that I was having with the population simulation question. I am sorry to be a pest, but something still isn't clicking.
Here is the code I have, I tried it two ways and I am getting two different error messages. I'm sorry, I am just trying to understand, and I am worried that if I search the internet I will just get more confused then I already am. My apologies.
x <- replicate(n=10, expr = (rnorm(n=10, mean = runif(1, 0, 10), sd=runif(1,0,10))))
mah.summary <- function(data.input, digits...){ sum.output <- matrix(NA, nrow = 1, ncol = ncol(x)) x <- data.input
sum.stats <- c("sum", "mean", "std.dev", "minumum", "maximum")
for (i in 1:ncol(x)){ sum.output[,i] <- apply(x, 2, sum) } return(sum.output) }
mah.summary(x, digits=2)
When just i on sum.sats Error in sum.output[, i] <- apply(x, 2, sum) : number of items to replace is not a multiple of replacement length
mah.summary <- function(data.input, digits...){ sum.output <- matrix(NA, nrow = 1, ncol = ncol(x)) x <- data.input
sum.stats <- c("sum", "mean", "std.dev", "minumum", "maximum")
for (i in 1:ncol(x)){ sum.output[,i] <- apply(x[i], 2, sum) } return(sum.output) }
mah.summary(x, digits=2) # Error in apply(x[i], 2, sum) : dim(X) must have a positive length
I originally didn't have it written as a loop and it calculated what I needed, however, when saving into the matrix it simply remade the matrix and stored the data, but not in their appropriate slots so I changed to writing a loop. AHHHH! I swear when it clicks it will click.
-Mal
— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/pearselab/r-intro-mahagadorn/issues/9#issuecomment-257396247, or mute the thread https://github.com/notifications/unsubscribe-auth/ABLcUs3cjchMRtJuwjszmBcTrCnUX3kvks5q5kJwgaJpZM4KlQoO .