[英]How to make wide format dataframe to long format in R?
I am trying to make a box plot out of a dataframe with 1000 rows and 80 columns.我正在尝试用 dataframe 制作一个盒子 plot,它有 1000 行和 80 列。 It currently looks like this.
目前看起来像这样。 enter image description here
在此处输入图像描述
Now I want to move each column to stack 80 different columns but not sure how to do that.现在我想移动每一列以堆叠 80 个不同的列,但不知道该怎么做。 How can I separate the columns and stack to make a wide format dataframe to a long format data?
如何分离列和堆栈以将宽格式 dataframe 转换为长格式数据?
Current dataframe looks like this:当前 dataframe 如下所示:
age1 age 2 age3
x1 y1 z1
x2 y2 z2
x3 y3 z3
Desired outcome is:期望的结果是:
age value
1 x1
1 x2
1 x3
1 x1
2 y1
2 y2
2 y3
3 z1
3 z2
3 z3
Suppose you have a dataframe like this:假设你有这样一个 dataframe:
dat <- data.frame(
age1 = c(1, 2, 3),
age2 = c(4, 5, 6),
age3 = c(7, 8, 9)
)
You can use 'pivot_longer' to get your desired outcome:您可以使用“pivot_longer”来获得您想要的结果:
library(tidyverse)
dat <- dat %>%
pivot_longer(cols = starts_with("age"),
names_to = "age",
names_prefix = "age",
values_to = "value") %>%
arrange(age)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.