[英]r wide to long to wide
This is a version of my dataset这是我的数据集的一个版本
ID Name n Mean_SD q2 q1_q3 Range
1 A 1477 3.42(15.12) 0.8 0.4,1.9 0 - 343.7
1 B 1475 127.114 (668.781) 0.8 3.5,29.3 0.071 - 16013.2
2 A 445 3.35(20.41) 0.5 0.3,1.25 0.1 - 343.7
2 B 446 113.142(817.681 ) 1.7 0.775,6.225 0.1 - 9518
How do I transform this to a long-wide format like this如何将其转换为像这样的长格式
Name Summary 1 2
A n 1477 445
Mean_SD 3.42(15.12) 3.35(20.41)
q2 0.8 0.5
q1_q3 0.4,1.9 0.3,1.25
Range 0 - 343.7 0.1 - 343.7
B n 1475 446
Mean_SD 127.114 (668.781) 113.142(817.681 )
q2 0.8 1.7
q1_q3 3.5,29.3 0.775,6.225
Range 0.071 - 16013.2 0.1 - 9518
Please note the Id is transformed to Wide from Long,请注意,Id 从 Long 转换为 Wide,
n Mean_SD q2 q1_q3 Range are transformed to long from wide. n Mean_SD q2 q1_q3 范围从宽转换为长。
Any suggestions much appreciated.任何建议都非常感谢。 Thanks in advance.提前致谢。
Use tidyr::pivot_longer
and then tidyr::pivot_wider
.使用tidyr::pivot_longer
然后tidyr::pivot_wider
。 Note that you'll have to make sure all columns are the same class to do this.请注意,您必须确保所有列都相同 class 才能执行此操作。
df <- structure(list(ID = c(1, 1, 2, 2), Name = c("A", "B", "A", "B"
), n = c("1477", "1475", "445", "446"), Mean_SD = c("3.42(15.12)",
"127.114(668.781)", "3.35(20.41)", "113.142(817.681)"), q2 = c("0.8",
"0.8", "0.5", "1.7"), q1_q3 = c("0.4,1.9", "3.5,29.3", "0.3,1.25",
"0.775,6.225"), Range = c("0-343.7", "0.071-16013.2", "0.1-343.7",
"0.1-9518")), row.names = c(NA, -4L), class = c("tbl_df", "tbl",
"data.frame"))
library(dplyr)
library(tidyr)
df %>%
pivot_longer(c(n, Mean_SD, q2, q1_q3, Range), names_to = 'Summary') %>%
pivot_wider(names_from = ID)
# A tibble: 10 × 4
Name Summary `1` `2`
<chr> <chr> <chr> <chr>
1 A n 1477 445
2 A Mean_SD 3.42(15.12) 3.35(20.41)
3 A q2 0.8 0.5
4 A q1_q3 0.4,1.9 0.3,1.25
5 A Range 0-343.7 0.1-343.7
6 B n 1475 446
7 B Mean_SD 127.114(668.781) 113.142(817…
8 B q2 0.8 1.7
9 B q1_q3 3.5,29.3 0.775,6.225
10 B Range 0.071-16013.2 0.1-9518
You can read more about the pivoting functions here您可以在此处阅读有关旋转功能的更多信息
In addition to @Richard Berry s correct answer:除了@Richard Berry 的正确答案:
library(gt)
library(dplyr)
library(tidyr)
df %>%
mutate(across(-Name, as.character)) %>%
pivot_longer(-c(ID, Name),
names_to = "Summary") %>%
pivot_wider(names_from = ID) %>%
group_by(Name) %>%
mutate(Name = ifelse(row_number()==1, Name, "")) %>%
ungroup() %>%
gt()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.