#size of 10
sd1<-matrix(0,nrow=10,ncol=100)
for (i in 1:100){
sd1[,i]<-rnorm(10, 0, 1)
}
x1<-apply(sd1,MARGIN=2,FUN=mean)
x10<-mean(x1)
cat('x10=',x10)
Size of 100
sd2<-matrix(0,nrow=100,ncol=100)
for (i in 1:100){
sd2[,i]<-rnorm(100)
}
x2<-apply(sd2,MARGIN=2,FUN=mean)
x100<-mean(x2)
cat('x100=',x100)
Hello, I have created two matrices containing each sample from 100 samples of size 10 from a standard normal distribution and 100 samples of size 100. I want to transfer them into a data frame and calculate the mean for each sample.
I tried to use as.data.frame to directly convert the matrix, but I got different row/column numbers in dataframe. So I wonder how can I convert matrix into a data frame and calculate the mean for each sample in a matrix or dataframe.
s1<-as.data.frame(t(sd1))
Many thanks ahead!
CodePudding user response:
Are you looking for each matrix row to be a column in the data frame? So the dataframe would be 10 columns and 100 observations each?
This isn't the most efficient way to do this but you could just built out the matrix in the tibble() function. And then you can use the summary() to get descriptive stats for all columns.
library(tidyverse)
df <-
tibble(
sample1 = sd1[1,],
sample2 = sd1[2],
sample3 = sd1[3],
sample4 = sd1[4],
sample5 = sd1[5],
sample6 = sd1[6],
sample7 = sd1[7],
sample8 = sd1[8],
sample9 = sd1[9],
sample10 = sd1[10]
)
summary(df)
Another way to get the means is using pivot_longer() and summarize() as follows
df %>%
pivot_longer(
cols = c(1:10),
names_to = "sample_type",
values_to = "values"
) %>%
group_by(sample_type) %>%
summarize(sample_means = mean(values))