提问人:dia05 提问时间:11/13/2023 最后编辑:Maëldia05 更新时间:11/15/2023 访问量:62
沿对角线排列 DataFrame 的值
permute the values of a dataframe diagonally
问:
如何将数据帧数据转换为new_data?我用过pivot_longer和pivot_wider但我没有得到我想要的。
data <- data.frame(
ind = c("la", "lb", "lc"),
c1 = c(1, 2, 3),
c2 = c(4, 5, 6),
c3 = c(7, 8, 9),
c4 = c(10, 11, 12)
)
期望的结果
new_data <- data.frame(
ind = c("c1", "c2", "c3", "c4"),
la = c(1, 4, 7, 10),
lb = c(2, 5, 8, 11),
lc = c(3, 6, 9, 12)
)
答:
4赞
Maël
11/13/2023
#1
data.table::transpose
data.table::transpose(data, make.names = "ind", keep.names = "ind")
# ind la lb lc
# 1 c1 1 2 3
# 2 c2 4 5 6
# 3 c3 7 8 9
# 4 c4 10 11 12
sjmisc::rotate_df
:
sjmisc::rotate_df(data, cn = TRUE, rn = "ind")
tidyverse
的 s:pivot
library(dplyr)
library(tidyr)
data %>%
pivot_longer(-ind) %>%
pivot_wider(names_from = "ind") %>%
rename("ind" = name)
# ind la lb lc
# 1 c1 1 2 3
# 2 c2 4 5 6
# 3 c3 7 8 9
# 4 c4 10 11 12
评论
0赞
Friede
11/13/2023
从未听说过(+1)。感谢您让我们知道。sjmisc::rotate_df()
2赞
Friede
11/13/2023
#2
R base
据我所知,base 中没有类似 -like 的数据帧函数。一种方法:t()
R
R-base
x <- t(as.matrix(data))
colnames(x) <- x[1L, ]
x <- x[-1L, ]
x <- as.data.frame(cbind("ind" = rownames(x), x))
rownames(x) <- seq(nrow(x))
x
包装在一个小函数中:
transpose_df <- \(df) {
stopifnot(is.data.frame(df))
x <- t(as.matrix(df))
colnames(x) <- x[1, ]
x <- x[-1, ]
x <- as.data.frame(cbind("ind" = rownames(x), x))
rownames(x) <- seq(nrow(x))
x
}
给
data <- data.frame(
ind = c("la", "lb", "lc"),
c1 = c(1, 2, 3),
c2 = c(4, 5, 6),
c3 = c(7, 8, 9),
c4 = c(10, 11, 12)
)
transpose_df(data)
ind la lb lc
1 c1 1 2 3
2 c2 4 5 6
3 c3 7 8 9
4 c4 10 11 12
评论