Reputation: 95
I would like to do something like so:
I have many matrices that look as follows:
head(cluster1,n=10)
beg end IBI len durn mean.isis SI
[1,] 6 8 NA 3 0.109883 0.05494150 1
[2,] 10 22 0.363067 13 0.350182 0.02918183 1
[3,] 27 30 0.589205 4 0.128999 0.04299967 1
[4,] 31 36 0.292974 6 0.048144 0.00962880 1
[5,] 37 44 0.182525 8 0.227413 0.03248757 1
[6,] 45 47 0.130840 3 0.063720 0.03186000 1
[7,] 48 56 0.413761 9 0.182949 0.02286862 1
[8,] 59 65 0.475499 7 0.192862 0.03214367 1
[9,] 67 69 0.208579 3 0.027613 0.01380650 1
[10,] 70 74 0.116538 5 0.295098 0.07377450 1
head(cluster2,n=10)
beg end IBI len durn mean.isis SI
[1,] 1 4 NA 4 0.011045 0.003681667 1
[2,] 37 41 24.749159 5 0.037666 0.009416500 1
[3,] 47 49 4.622307 3 0.008638 0.004319000 1
[4,] 59 61 6.767432 3 0.008638 0.004319000 1
[5,] 64 67 3.499121 4 0.012178 0.004059333 1
[6,] 83 85 7.063805 3 0.007504 0.003752000 1
[7,] 89 91 2.827788 3 0.015576 0.007788000 1
[8,] 92 94 1.628137 3 0.007930 0.003965000 1
[9,] 95 97 0.576744 3 0.008638 0.004319000 1
[10,] 103 105 10.000201 3 0.009204 0.004602000 1
I would like to create a for loop where I create a list of the the mean values of each of the matrix's 5th row values.
mean(cluster1[,5])
[1] 0.2731692
mean(cluster2[,5])
[1] 0.01214404
It would give a result like so :
means(0.2731692,0.01214404)
What I tried to do:
means=''
for(i in 1:100){names.append(mean(str('cluster'+i)[,5]))}
This seems to not work as I hoped in R.
Any help is greatly appreciated!
Thanks
Upvotes: 0
Views: 59
Reputation: 101335
Another base R option with mget
, similar to the solution @Ronak Shah
sapply(lapply(mget(ls(pattern = "cluster")),`[[`,5),mean)
Upvotes: 1
Reputation: 388982
You can use mget
to get all matrices in a list and then get mean
of 5th column.
sapply(mget(paste0('cluster', 1:2)), function(x) mean(x[, 5]))
Replace 2
in 1:2
with number cluster
matrices that you have.
Upvotes: 2
Reputation: 1666
Try something like this:
means <- numeric(length = 100)
for (i in seq_len(length.out = 100))
{
means[i] <- mean(x = get(x = paste0("cluster", i))[, 5])
}
This will return a vector in this format: c(0.2731692,0.01214404, ...)
. If you want as a space separated string, do this:
paste0(means, collapse=" ")
Hope this helps.
Upvotes: 3