r - 如何使用gather()函数指定多列来整理数据

标签 r transpose tidyr tidyverse

我想用 Gather 功能整理我的数据,但如何一次指定多列?

说这是我的数据:

    Country Country.Code Year X0tot4 X5tot9 X10tot14 X15tot19 X20tot24
1  Viet Nam          704 1955   4606   2924     2389     2340     2502
2  Viet Nam          704 1960   5842   4410     2860     2356     2318
3  Viet Nam          704 1965   6571   5646     4328     2823     2335
4  Viet Nam          704 1970   7065   6391     5548     4271     2797
5  Viet Nam          704 1975   7658   6862     6237     5437     4208
6  Viet Nam          704 1980   7991   7473     6754     6113     5266
7  Viet Nam          704 1985   8630   7855     7375     6657     6027
8  Viet Nam          704 1990   9212   8513     7770     7277     6571
9  Viet Nam          704 1995   9200   9099     8447     7702     7140
10 Viet Nam          704 2000   7245   9119     9053     8402     7610
11 Viet Nam          704 2005   6760   7140     8997     8951     8257
12 Viet Nam          704 2010   7277   6657     7015     8891     8775
13 Viet Nam          704 2015   7753   7233     6623     6982     8817

现在我想创建一个新列 Age.groups来自 X0tot4 的变量至 X20tot24 .

类似 df %>% gather(key = "Age.group", value = c(4:8)) .控制台说这不是正确的列规范。但什么是?

最佳答案

gather功能,value指定结果中值列的名称;要指定收集哪些列,您可以使用 start_column:end_column语法,这将收集从 start_column 到 end_column 的所有列;在您的情况下,它将是 X0tot4:X20tot24 :

df %>% gather(key = 'Age.group', value = 'Value.name', X0tot4:X20tot24)
#                        V                     V
#                              V               V
#                                    V         V
#      Country Country.Code Year Age.group Value.name
#1   Viet Nam           704 1955    X0tot4       4606
#2   Viet Nam           704 1960    X0tot4       5842
#3   Viet Nam           704 1965    X0tot4       6571
#4   Viet Nam           704 1970    X0tot4       7065
#5   Viet Nam           704 1975    X0tot4       7658
#6   Viet Nam           704 1980    X0tot4       7991
#7   Viet Nam           704 1985    X0tot4       8630

关于r - 如何使用gather()函数指定多列来整理数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45966417/

相关文章:

r - 距离矩阵中缺失数据的插补

mysql - 加入 MySQL 时转置数据

r - 为什么在 tidyr::pivot_wider 中尝试使用 names_glue 时出现错误?

r - tidyr `fill()` 可以与 R 中的 if_else() 一起使用吗?

r - 如何找到两个时间向量的不同元素?

r - 如何在 R 中创建复杂的气泡图

pivot - SQL 将行转置为列(按键变量分组)?

mysql - 将记录转置为 mysql 中 3 个表的记录

R tidyr : use separate function to separate character column with comma-separated text into multiple columns using RegEx

r - 根据 R 中表格的列数过滤列表