SamPassmore
SamPassmore

Reputation: 1365

Getting pairs of columns from a list of data frames

I have a list of data frames

q = list(x = data.frame(a = 1:3, b = 4:6),
         y = data.frame(c = letters[1:3], d = letters[4:6]))

I need to pair each column from data frame x to each column of data frame y

So that the results would be a named list looking something like:

ac
1  a
2  b
3  c
ad
1  d
2  e
3  f  
bc
4  a
5  b
6  c
bd
4  d
5  e
6  f

The result needs to be applied to a list that has n data frames with each data frame having k columns

Thanks,

Sam

Upvotes: 2

Views: 64

Answers (1)

Nathan Werth
Nathan Werth

Reputation: 5273

I capitalized the column names to prevent any confusion with their values, and added another data.frame with 3 columns to make sure this way is general enough.

q = list(x = data.frame(A = 1:3, B = 4:6),
         y = data.frame(C = letters[1:3], D = letters[4:6]),
         z = data.frame(E = 3:1, G = letters[3:1], H = letters[6:4]))
col_counts <- lengths(q)
col_indices <- lapply(col_counts, seq)
matchups <- do.call(expand.grid, col_indices)

get_nth_name <- function(x, n) {
  names(x)[n]
}

index_over <- function(indexes, datalist = q) {
  column_values <- mapply('[[', datalist, indexes, SIMPLIFY = FALSE)
  names(column_values) <- mapply(get_nth_name, datalist, indexes)
  as.data.frame(column_values)
}

result <- apply(matchups, 1L, index_over)
names(result) <- vapply(
  result,
  FUN.VALUE = character(1),
  FUN = function(x) {
    paste0(names(x), collapse = '')
  }
)

Upvotes: 2

Related Questions