[英]Stack every other column in R
I'm looking to stack every other column under the previous column in R.我希望在 R 中的前一列下堆叠所有其他列。 Any suggestions?有什么建议么?
For example:例如:
c1 c1 | c2 c2 | c3 c3 | c4 c4 |
---|---|---|---|
A一个 | 1 1 | D D | 4 4 |
B乙 | 2 2 | E乙 | 5 5 |
C C | 3 3 | F F | 6 6 |
dat <- data.frame(
c1 = c("A", "B", "C"),
c2 = c(1, 2, 3),
c3 = c("D", "E", "F"),
c4 = c(4, 5, 6))
To look like this:看起来像这样:
c1 c1 | c2 c2 |
---|---|
A一个 | D D |
1 1 | 4 4 |
B乙 | E乙 |
2 2 | 5 5 |
C C | F F |
3 3 | 6 6 |
dat2 <- data.frame(
c1 = c("A", 1, "B", 2, "C", 3),
c2 = c("D", 4, "E", 5, "F", 6))
Thanks in advance.提前致谢。
A basic way with stack()
: stack()
的基本方法:
as.data.frame(sapply(seq(1, ncol(dat), 2), \(x) stack(dat[x:(x+1)])[[1]]))
# V1 V2
# 1 A D
# 2 B E
# 3 C F
# 4 1 4
# 5 2 5
# 6 3 6
You could also rename the data with a structural foramt and pass it into tidyr::pivot_longer()
:您还可以使用结构格式重命名数据并将其传递给tidyr::pivot_longer()
:
library(dplyr)
library(tidyr)
dat %>%
rename_with(~ paste0('c', ceiling(seq_along(.x) / 2), '_', 1:2)) %>%
mutate(across(, as.character)) %>%
pivot_longer(everything(), names_to = c(".value", NA), names_sep = '_')
# # A tibble: 6 × 2
# c1 c2
# <chr> <chr>
# 1 A D
# 2 1 4
# 3 B E
# 4 2 5
# 5 C F
# 6 3 6
The rename
line transforms c1 - c4
to c1_1, c1_2, c2_1, c2_2
. rename
行将c1 - c4
转换为c1_1, c1_2, c2_1, c2_2
。
For an even numbered number of columns you can do something like:对于偶数列,您可以执行以下操作:
do.call(cbind, lapply(seq(length(dat)/2), \(x) stack(dat[ ,x + ((x-1):x)])[1])) |>
set_names(names(dat)[seq(length(dat)/2)])
c1 c2
1 A D
2 B E
3 C F
4 1 4
5 2 5
6 3 6
This gets the first column when calling stack
and cbinds
all the stacked columns.这会在调用stack
并cbinds
所有堆叠的列时获取第一列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.