gpt4 book ai didi

r - 将多个标题表转换为长格式

转载 作者:行者123 更新时间:2023-12-04 21:30:43 24 4
gpt4 key购买 nike

我正在阅读具有多行标题的 Excel 表格,该表格通过 read.csv 在 中创建一个像这样的对象R .

R1 <- c("X", "X.1", "X.2", "X.3", "EU", "EU.1", "EU.2", "US", "US.1", "US.2")
R2 <- c("Min Age", "Max Age", "Min Duration", "Max Duration", "1", "2", "3", "1", "2", "3")
R3 <- c("18", "21", "1", "3", "0.12", "0.32", "0.67", "0.80", "0.90", "1.01")
R4 <- c("22", "25", "1", "3", "0.20", "0.40", "0.70", "0.85", "0.98", "1.05")
R5 <- c("26", "30", "1", "3", "0.25", "0.50", "0.80", "0.90", "1.05", "1.21")
R6 <- c("18", "21", "4", "5", "0.32", "0.60", "0.95", "0.99", "1.30", "1.40")
R7 <- c("22", "25", "4", "5", "0.40", "0.70", "1.07", "1.20", "1.40", "1.50")
R8 <- c("26", "30", "4", "5", "0.55", "0.80", "1.09", "1.34", "1.67", "1.99")
table1 <- as.data.frame(rbind(R1, R2, R3, R4, R5, R6, R7, R8))

我现在如何“压平”它,以便最终得到 R 包含“Min age”、“Max Age”、“Min Duration”、“Max Duration”、“Area”、“Level”、“Price”列的表格。 “区域”列显示“欧盟”或“美国”,“级别”列显示 1、2 或 3,然后“价格”列显示 Excel 表格中的相应价格?

如果没有多个标题行,我会使用 tidyr 的收集功能,但似乎无法使用这些数据,有什么想法吗?

输出应该有总共 36 行 + 标题

最佳答案

如果按照 akrun 的建议跳过第一行,您可能会得到如下所示的数据:(R 自动添加了“X”s 和“.1”/“.2”)

library(tidyverse)

df <- tribble(
~Min.Age, ~Max.Age, ~Min.Duration, ~Max.Duration, ~X1.1, ~X2.1, ~X3.1, ~X1.2, ~X2.2, ~X3.2,
"18", "21", "1", "3", "0.12", "0.32", "0.67", "0.80", "0.90", "1.01",
"22", "25", "1", "3", "0.20", "0.40", "0.70", "0.85", "0.98", "1.05",
"26", "30", "1", "3", "0.25", "0.50", "0.80", "0.90", "1.05", "1.21",
"18", "21", "4", "5", "0.32", "0.60", "0.95", "0.99", "1.30", "1.40",
"22", "25", "4", "5", "0.40", "0.70", "1.07", "1.20", "1.40", "1.50",
"26", "30", "4", "5", "0.55", "0.80", "1.09", "1.34", "1.67", "1.99"
)

有了这些数据,您就可以使用 gather将所有以 X 开头的标题收集到一列中,并将价格收集到另一列中。您可以 separate将标题放入“级别”和“区域”。最后,重新编码区域并从关卡中删除“X”。

df %>% 
gather(headers, Price, starts_with("X")) %>%
separate(headers, c("Level", "Area")) %>%
mutate(Area = if_else(Area == "1", "EU", "US"),
Level = parse_number(Level))
#> # A tibble: 36 x 7
#> Min.Age Max.Age Min.Duration Max.Duration Level Area Price
#> <chr> <chr> <chr> <chr> <dbl> <chr> <chr>
#> 1 18 21 1 3 1 EU 0.12
#> 2 22 25 1 3 1 EU 0.20
#> 3 26 30 1 3 1 EU 0.25
#> 4 18 21 4 5 1 EU 0.32
#> 5 22 25 4 5 1 EU 0.40
#> 6 26 30 4 5 1 EU 0.55
#> 7 18 21 1 3 2 EU 0.32
#> 8 22 25 1 3 2 EU 0.40
#> 9 26 30 1 3 2 EU 0.50
#> 10 18 21 4 5 2 EU 0.60
#> # ... with 26 more rows

创建于 2018-10-12 由 reprex package (v0.2.1)

附言您可以在这里找到许多电子表格处理工作流程: https://nacnudus.github.io/spreadsheet-munging-strategies/small-multiples-with-all-headers-present-for-each-multiple.html

关于r - 将多个标题表转换为长格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52785436/

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