Question: comment on the code #create a list . . . N < - 1 0 0 X < - vector ( list ,

comment on the code #create a list ...
N <-100
X <- vector("list", N)
for (i in 1:N){
name <- paste0("n", i)
vect <- rnorm(5, mean =20, sd =10)
X[[i]]<- list(name = name, vect = vect)
}
#show the structure of X
str(X)
# Compute the sum of the values of vect in each slot
sums_vect <- sapply(X, function(x) sum(x$vect))
print(sums_vect)
# Create a matrix M of size 100x5
M <- do.call(rbind, lapply(X, function(x) x$vect))
print(M)
# Compute the sums by columns of M
column_sums <- numeric(ncol(M))
for (j in 1:ncol(M)){
column_sums[j]<- sum(M[, j])
}
print(column_sums)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Finance Questions!