gpt4 book ai didi

根据列名称模式 reshape 数据

转载 作者:行者123 更新时间:2023-12-02 01:51:49 24 4
gpt4 key购买 nike

df <- structure(list(`1.tes1` = 8.00073085700465, `1.tes2` = 8.08008192865136, 
`1.tes3` = 7.67643993710322, `1.tes4` = 4.40797764861845,
`1.tes5` = 8.07887886210789, `1.tes6` = 7.5133416960745,
`2.tes1` = 8.85382519278079, `2.tes2` = 7.69705180134625,
`2.tes3` = 7.23033538475091, `2.tes4` = 8.14366028991503,
`2.tes5` = 8.00207221069391, `2.tes6` = 7.04604929055087,
`3.tes1` = 5.56967515444227, `3.tes2` = 6.81971790904382,
`3.tes3` = 7.69285459160427, `3.tes4` = 7.29436429730407,
`3.tes5` = 7.39693058270568, `3.tes6` = 6.6688956545532,
`4.tes1` = 7.02870405956919, `4.tes2` = 7.89704902680482,
`4.tes3` = 7.207699266581, `4.tes4` = 8.07642509042209, `4.tes5` = 9.12013776731989,
`4.tes6` = 8.73388960806046), row.names = c(NA, -1L), class = c("tbl_df",
"tbl", "data.frame"))

上面是我的示例数据,列名的模式类似于a.bc,其中a是组ID,b是变量名称,c是复制id,因此3.tes6表示组3,变量tes,复制6.

我想将 df reshape 为一个数据框(更好地使用 tidyverse 包):

Group Variable Replication Value
1 tes 1 8.001
1 tes 2 8.080
...
3 tes 5 7.400
3 tes 6 6.669
...
4 tes 6 8.734

最佳答案

在pivot_longer中使用names_pattern=:

library(dplyr)
library(tidyr)

df %>%
pivot_longer(everything(),
names_to = c("Group", "Variable", "Replication"),
values_to = "Value",
names_pattern = "(\\d+)\\.(\\D+)(\\d+)",
names_transform = list(Group = as.integer,
Replication = as.integer))

给予:

# A tibble: 24 x 4
Group Variable Replication Value
<int> <chr> <int> <dbl>
1 1 tes 1 8.00
2 1 tes 2 8.08
3 1 tes 3 7.68
4 1 tes 4 4.41
5 1 tes 5 8.08
6 1 tes 6 7.51
7 2 tes 1 8.85
8 2 tes 2 7.70
9 2 tes 3 7.23
10 2 tes 4 8.14
# ... with 14 more rows

关于根据列名称模式 reshape 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70171043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com