Michale
Michale

Reputation: 131

How to use loop to add numbers to a group of tables' name in r

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 ?

Upvotes: 0

Views: 130

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145785

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, ")"))
}

Upvotes: 3

Related Questions