1

I have the following dynamic list created with the names cluster_1, cluster_2... like so:

observedUserShifts <- vector("list")
cut <- 2

for (i in 1:cut) {
   assign(paste('cluster_', i, sep=''), subset(sortedTestRTUser, cluster==i))
   observedUserShifts[[i]] <- mean(cluster_1$shift_length_avg)
}

Notice that i have cut=2 so 2 lists are created dynamically with the names due to the 'assign' function: cluster_1 and cluster_2

I want to invoke each of the above lists within the for loop. Notice that i have hard coded cluster_1 in the for loop (2nd line inside for loop). How do I change this so that this is not hard coded?

I tried:

> observedUserShifts[[i]] <- mean((paste('cluster_','k',sep='')$shift_length_avg)
+ )
Error in paste("cluster_", "k", sep = "")$shift_length_avg : 
$ operator is invalid for atomic vectors
Rookie
  • 5,179
  • 13
  • 41
  • 65
  • 2
    This is not a good way to find the mean within each cluster, for multiple reasons. Instead, use aggregate, data.table, or dplyr, as described [in this question](http://stackoverflow.com/questions/21982987/mean-per-group-in-a-data-frame) – David Robinson Dec 24 '15 at 00:02
  • For example, you could simply do `library(dplyr); sortedTestRTUser %>% group_by(cluster) %>% summarize(observedUserShifts = mean(shift_length_avg))` – David Robinson Dec 24 '15 at 00:04

1 Answers1

0

Agree this is suboptimal coding practice, but to answer the specific question, use get:

for (i in 1:cut) {
   assign(paste('cluster_', i, sep=''), subset(sortedTestRTUser, cluster==i))
   observedUserShifts[[i]] <- 
             mean( get(paste('cluster_', i, sep='') )[['shift_length_avg']] )
}

Notice that instead of using $ I chose to use [[ with a quoted column name.

IRTFM
  • 258,963
  • 21
  • 364
  • 487