Reputation: 3
Hi I have made a function Get to calculate the mean and SD from a data set, I have seven data sets of the same format and want to put the output applying the Get function to these data sets in one matrix to compare. I know I need one more step in my function but cannot figure it out? Also id there away to loop this over each data set automatically if the names are CA1, CA2, ...? I am new to R
This is the function
Get <- function (x) {
x <- as.matrix(x)
m <- mean(x[,3:4])
SD <- sd(x[,3:4])
return(list(mean=m, SD=SD))
}
Upvotes: 0
Views: 100
Reputation: 887028
Try:
set.seed(42) #creating some datasets
CA1 <- as.data.frame(matrix(sample(1:20, 5*20, replace=TRUE), ncol=5))
CA2 <- as.data.frame(matrix(sample(1:20, 5*20, replace=TRUE), ncol=5))
CA3 <- as.data.frame(matrix(sample(1:20, 5*20, replace=TRUE), ncol=5))
nm1 <- ls(pattern="^CA\\d")
res <- sapply(mget(nm1), Get)
res #here you get a list of `6`
# CA1 CA2 CA3
#mean 10.1 9.9 9.275
#SD 6.058687 5.490318 5.579208
To convert to matrix
m1 <- matrix(unlist(res), ncol=3, dimnames=dimnames(res))
m1
# CA1 CA2 CA3
#mean 10.100000 9.900000 9.275000
#SD 6.058687 5.490318 5.579208
Upvotes: 1