我有一个数据框列表
q = list(x = data.frame(a = 1:3, b = 4:6),
y = data.frame(c = letters[1:3], d = letters[4:6]))
我需要将数据帧x中的每一列与数据帧y的每一列配对
因此,结果将是一个命名列表,如下所示:
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
结果需要应用于具有n个数据帧的列表,每个数据帧具有k列
谢谢,
萨姆
答案 0 :(得分:2)
我将列名大写以防止与其值混淆,并添加了另一个包含3列的data.frame,以确保这种方式足够通用。
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 = '')
}
)