Home > OS >  How to cbind two series of array in to one dataframe by for loop in R
How to cbind two series of array in to one dataframe by for loop in R

Time:04-29

I have two series of array, pan1,pqn2,,,pn30 and read1,read2,,,read30, I want to cbind them into one dataframe with colnames like pan1,read1,pan2,read2,,,pan30,read30 by a for loop in R, how should I do? Here's my try but doesn't work

pan <- objects(pattern='^pan[0-9] $')
read <- objects(pattern = '^read[0-9] $')
for (i in 1:30) {
       for (j in 1:30) {
            if (i==j) {
                  panread <- cbind(pan[i],read[j]) 
        }
       }
      }

CodePudding user response:

one solution in base R:

generate vector of objects' names observing the pattern pan1, read1, ..., pan30, read30

objects_to_bundle <- as.vector(matrix(c(objects(pattern = '^pan*'),
                                        objects(pattern = '^read*')
                                        ),,2, byrow = TRUE
                               )
                     )

get a list of the objects by lapply as follows: get objects by object name, convert this into a named structure (list) and return this list as.data.frame (which is a rectangular list of columns anyway):

as.data.frame(structure(.Data = lapply(objects_to_bundle,
                                       function(n) as.vector(get(n))
                                       ),
                        .Names = objects_to_bundle
                        )
              )
  • Related