user7182686
user7182686

Reputation:

Adding a suffix to names when storing results in a loop

I am making some plots in R in a for-loop and would like to store them using a name to describe the function being plotted, but also which data it came from.

So when I have a list of 2 data sets "x" and "y" and the loop has a structure like this:

x = matrix(
  c(1,2,4,5,6,7,8,9),
  nrow=3,
  ncol=2)

y = matrix(
  c(20,40,60,80,100,120,140,160,180),
  nrow=3,
  ncol=2)

data <- list(x,y)

for (i in data){
  ??? <- boxplot(i)
}

I would like the ??? to be "name" + (i) + "_" separator. In this case the 2 plots would be called "plot_x" and "plot_y".

I tried some stuff with paste("plot", names(i), sep = "_") but I'm not sure if this is what to use, and where and how to use it in this scenario.

Upvotes: 1

Views: 873

Answers (2)

abcxyz
abcxyz

Reputation: 81

akrun is right, you should try to avoid setting names in the global environment. But if you really have to, you can try this,

> y = matrix(c(20,40,60,80,100,120,140,160,180),ncol=1)
> .GlobalEnv[[paste0("plot_","y")]] <- boxplot(y)
> str(plot_y)
List of 6
 $ stats: num [1:5, 1] 20 60 100 140 180
 $ n    : num 9
 $ conf : num [1:2, 1] 57.9 142.1
 $ out  : num(0)
 $ group: num(0)
 $ names: chr "1"

You can read up on .GlobalEnv by typing in ?.GlobalEnv, into the R command prompt.

Upvotes: 0

akrun
akrun

Reputation: 886948

We can create an empty list with the length same as that of the 'data' and then store the corresponding output from the for loop by looping over the sequence of 'data'

out <- vector('list', length(data))    
for(i in seq_along(data)) {
      out[[i]] <- boxplot(data[[i]])
  }

str(out)
#List of 2
# $ :List of 6
#  ..$ stats: num [1:5, 1:2] 1 1.5 2 3 4 5 5.5 6 6.5 7
#  ..$ n    : num [1:2] 3 3
#  ..$ conf : num [1:2, 1:2] 0.632 3.368 5.088 6.912
#  ..$ out  : num(0) 
#  ..$ group: num(0) 
#  ..$ names: chr [1:2] "1" "2"
# $ :List of 6
#  ..$ stats: num [1:5, 1:2] 20 30 40 50 60 80 90 100 110 120
#  ..$ n    : num [1:2] 3 3
#  ..$ conf : num [1:2, 1:2] 21.8 58.2 81.8 118.2
#  ..$ group: num(0) 
#  ..$ names: chr [1:2] "1" "2"

If required, set the names of the list elements with the object names

names(out) <- paste0("plot_", c("x", "y"))

It is better not to create multiple objects in the global environment. Instead as showed above, place the objects in a list

Upvotes: 1

Related Questions