0

I want to get those tables with same name added numbers by combining two columns from different tables (only one column in each table). part of code is like this( I don't know how many tables in advance. So I have to use n input by users)

for(i in 1: n)
      { 
   data[i]<-data.frame(X=X[i],Y=Y[i])

}

I want to get like

data1  is (X1,Y1)
data2  is (X2,Y2)
....   is ....

In addition. after create those tables data1,data2...
then how to use a general expression to print them one by one?

I know it does not work. But How to do it ?

Michale
  • 131
  • 6
  • 1
    Consider [putting your data frames in a list](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207) – Gregor Thomas May 21 '20 at 03:26
  • but I don't know how many tables in advace. – Michale May 21 '20 at 03:28
  • That shouldn't matter. If you want all tables named `data`, `data_list = mget(ls(pattern = "data[0-9]+"))`, or something like that. But it might be even nicer to put them in a list from the start so that `data1`, `data2`, `data3` are never created, instead `data_list[[1]]`, `data_list[[2]]`.... – Gregor Thomas May 21 '20 at 03:31
  • Would you please help me out with code for n tables? I mean examples – Michale May 21 '20 at 03:32
  • What is `X` and `Y` ? Do you want to create `n` dataframes named `data1`, `data2` etc based on user input `n`? – Ronak Shah May 21 '20 at 03:36
  • yes. X and Y are tables which also have X[1],X[2].... Y[1],Y[2].. – Michale May 21 '20 at 03:38
  • I tried Gregor's solution. it works. We can use list to store those tables. – Michale May 21 '20 at 03:41

1 Answers1

3

Try this:

data_list <- list()
for(i in 1: n) { 
   data_list[[i]] <- data.frame(X = X[i], Y = Y[i])
}

## alternately, if `X` and `Y` are data frames
data_list <- split(cbind(X, Y), 1:n) 

Printing is easier if we don't put things in separate data frames:

print(paste0("data", 1:n, " is (", X[[1]], ", ", Y[[1]], ")"))

But you can still do it:

for(i in 1:n) {
  print(paste0("data", i, " is (", data_list[[i]]$X, ", ", data_list[[i]]$Y, ")"))
}
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • 1
    If `X` and `Y` are dataframes and number of rows in them is greater than `n` `split` might give unexpected results. Maybe safer, `x <- seq_len(n); data_list <- split(cbind(X[x,], Y[x,]), x)` – Ronak Shah May 21 '20 at 03:46
  • Got it. Many thanks. I am trying to plot using generated new tables. – Michale May 21 '20 at 03:52