1

I have the following R code which creates 5 objects dynamically with names such as cluster1_dataset, ...., cluster5_dataset as follows:

# Extract cluster data
for (i in 1:K) {
  assign(paste("cluster",i,"_dataset",sep=""), subset(clustered_input_dataset, cluster == i))
}

How do i access these 5 dynamically created objects in R?

I have tried the following:

# Plot histograms & boxplots for each cluster to look at shift_length_avg   frequency distribution
par(mfrow=c(K,2))
for (i in 1:K) {
# Analyze cluster#1
  hist(dataset$shift_length_avg)
}

which gives me the following error:

Error in dataset$shift_length_avg : 
 $ operator is invalid for atomic vectors
Rookie
  • 5,179
  • 13
  • 41
  • 65
  • 6
    You really should not have to use `assign()` and `paste()` if you are new to R. That's usually a sign you are not doing things in the R-like way. you probably should have named lists which you can easily index via `[[ ]]` – MrFlick Dec 21 '15 at 20:17
  • 1
    Put the subsets in a list: `K.list <- lapply(1:K, function(i) subset(clustered_input_dataset, cluster==i))`. Eventuall you are looking for `split()`. `K.list <- split(clustered_input_dataset, clustered_input_dataset$cluster)` – jogo Dec 21 '15 at 20:18
  • 1
    Or even use lapply and split: 'lapply(split(clustered_input_dataset$shift_length_avg, clustered_input_dataset$cluster), hist)` – Heroka Dec 21 '15 at 20:20
  • [See here](http://stackoverflow.com/q/17499013/903061) for more tips on using lists of data frames. – Gregor Thomas Dec 21 '15 at 20:23

1 Answers1

1

The assign() function has a twin called get(). This is the function that you need. Refer to this concise and easy-to-understand article here.