如何用dplyr/tidyr转换数据框:重构含metric列的表格
Got it, reshaping your wide data into the long format you need is straightforward using tidyr::pivot_longer() (part of the tidyverse, which works seamlessly with dplyr). Here's how to do it:
First, assuming you already have your dat data frame set up as you showed, you can use this code to pivot the numeric columns into a metric column while keeping your identifier columns (group, temp, temp2) intact:
library(tidyr) library(dplyr) # Convert wide to long format dat_long <- dat %>% pivot_longer( cols = c(num, calc1, calc2), # Which columns to pivot into the metric column names_to = "metric", # Name of the new column for metric labels values_to = "value" # Name of the new column holding the metric values )
Resulting Data Frame
When you run this, dat_long will look like this:
# A tibble: 9 × 5 group temp temp2 metric value <chr> <chr> <chr> <chr> <dbl> 1 A GG ll num 1 2 A GG ll calc1 4 3 A GG ll calc2 7 4 B HH pp num 2 5 B HH pp calc1 5 6 B HH pp calc2 8 7 C KK rr num 3 8 C KK rr calc1 6 9 C KK rr calc2 9
Alternative (Older Function)
If you're more familiar with the older gather() function (now superseded by pivot_longer()), you can also use this equivalent code:
dat_long <- dat %>% gather(key = "metric", value = "value", num, calc1, calc2)
Either way, you'll get the exact structure you wanted—with a metric column containing num, calc1, calc2, and all your original identifier columns preserved.
内容的提问来源于stack exchange,提问作者user3022875

