Hi there. First post, please pardon any inaccuracies.
So I've created a function which accepts a matrix as an argument, does some computations and inputs the results into another matrix. Unfortunately, the code runs with the infamous error:
Error in result_matrix[i, ] <- b3 : **
** number of items to replace is not a multiple of replacement length
Below is the code for the function in question
descriptive_stats <- function(x){
n <- ncol(x)
result_matrix <- matrix(0,nrow = n, ncol=8)
for (i in 1:n) {
y <- x[,i]
N <- length(y)
M <- mean(y, na.rm = T)
s.d <- sd(y, na.rm = T)
cv <- 100 * s.d/M
Min <- min(y, na.rm = T)
Max <- max(y, na.rm = T)
std_error <- sd(y)/sqrt(length(y))
range_val <- range(y, na.rm = T)
b3 <- c(N,M,s.d,cv,Min,Max,std_error,range_val)
result_matrix[i,] <- b3
}
colnames(result_matrix) <- c("N","Mean","sd","cv","Min","Max","Stderror","Range")
rownames(result_matrix) <- colnames(x) # row names for results = column names of data
result_matrix <- round(result_matrix,2)
print(result_matrix)
The code that's generating the error
dataset <- matrix(rnorm(500, mean = 2, sd = 3), nrow = 100, ncol = 5)
descriptive_stats(dataset)
Any help will be deeply appreciated. Thanks in advance!