Pivot_longer 6 列到 3 列 [英] Pivot_longer 6 columns to 3 columns
问题描述
我知道我的问题很简单,但我整个上午都在尝试,但我无法理解.
I know my question is simple but I've trying all morning and I can't get my head around it.
我有这个数据框:
GeneID Gene.Symbol01 Ratio.2h Ratio.6h Ratio.10h Ratio.24h Pvalue_2h
1 174 FUT -0.23618761 -0.3276162 -0.1366940 -4.4899131 0.49045105
Pvalue_6h Pvalue_10h Pvalue_24h
1 0.06128851 0.59995612 0.0001798584
而且我需要对除 GeneID 和 GeneSymbol 之外的所有列进行 pivot_longer.生成的数据框应该有 3 个新列.一时间:2h、6h、10h和24h.然后还有两列包含比率值,另一列包含 pvalues.
And I need to pivot_longer all columns except GeneID and GeneSymbol. The resulting data frame should have 3 new columns. One with time: 2h, 6h, 10h, and 24h. Then two more columns with the ratio values and another one with the pvalues.
我知道这应该通过结合 names_to 和 names_pattern 来完成.我尝试了很多东西,但我无法做到.
I know this should be done with a combinametion of names_to and names_pattern. I have tried many things but I can't get it.
我尝试过的最后一件事是:
Last thing I have tried was this:
pivot_longer(cols = -c(GeneID, Gene.Symbol01),
names_to = c("Time", ".value"),
names_pattern = "_")
输入:
structure(list(GeneID = 174, Gene.Symbol01 = "FUT", Ratio.2h = -0.23618761,
Ratio.6h = -0.3276162, Ratio.10h = -0.136694, Ratio.24h = -4.4899131,
Pvalue_2h = 0.49045105, Pvalue_6h = 0.06128851, Pvalue_10h = 0.59995612,
Pvalue_24h = 0.0001798584), row.names = c(NA, -1L), class = c("tbl_df",
"tbl", "data.frame"))
推荐答案
使用 tidyverse
您可能希望 pivot_longer
Ratio.2h
中的所有变量> 到 Pvalue_24h
,然后 separate
分成 2 列.
Using tidyverse
you might want to pivot_longer
all variable from Ratio.2h
to Pvalue_24h
, then separate
it into 2 columns.
library(tidyverse)
DF %>%
pivot_longer(Ratio.2h:Pvalue_24h, names_to = "var") %>%
separate(var, into = c("type", "time"), sep = "_|\\.")
# # A tibble: 8 x 5
# GeneID Gene.Symbol01 type time value
# <dbl> <chr> <chr> <chr> <dbl>
# 1 174 FUT Ratio 2h -0.236
# 2 174 FUT Ratio 6h -0.328
# 3 174 FUT Ratio 10h -0.137
# 4 174 FUT Ratio 24h -4.49
# 5 174 FUT Pvalue 2h 0.490
# 6 174 FUT Pvalue 6h 0.0613
# 7 174 FUT Pvalue 10h 0.600
# 8 174 FUT Pvalue 24h 0.000180
然后,使用 pivot_wider
DF %>%
pivot_longer(Ratio.2h:Pvalue_24h, names_to = "var") %>%
separate(var, into = c("type", "time"), sep = "_|\\.") %>%
pivot_wider(names_from = "type", values_from = "value")
# # A tibble: 4 x 5
# GeneID Gene.Symbol01 time Ratio Pvalue
# <dbl> <chr> <chr> <dbl> <dbl>
# 1 174 FUT 2h -0.236 0.490
# 2 174 FUT 6h -0.328 0.0613
# 3 174 FUT 10h -0.137 0.600
# 4 174 FUT 24h -4.49 0.000180
数据
DF <- tribble(~GeneID, ~Gene.Symbol01, ~Ratio.2h, ~Ratio.6h, ~Ratio.10h, ~Ratio.24h, ~Pvalue_2h,~Pvalue_6h, ~Pvalue_10h, ~Pvalue_24h,
174, "FUT", -0.23618761, -0.3276162, -0.1366940, -4.4899131, 0.49045105,0.06128851, 0.59995612, 0.0001798584)
这篇关于Pivot_longer 6 列到 3 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!