我如何将按共同年份的行排列到R中的单独列中?

问题描述 投票:1回答:1

我对R比较陌生,但曾与dplyr进行数据转换。

我有一个数据行,其中包含年份和数字。

row     year    int

1       2020    100
2       2020    150
3       2020    300
4       2020    750
5       2020    555
6       2019    179
7       2019    233
8       2019    399
9       2019    400
10      2019    543

我如何按年份将这些行按行顺序分组,但又按列进行分组?如:

year    col1    col2    col3    col4    col5

2020    100     150     300     750     555
2021    179     233     399     400     543

这应该很简单,但是我似乎无法弄清楚如何使用dplyr或baseR。谢谢,

r
1个回答
1
投票

我们可以按'year'创建一个序列列,然后转向'wide'格式

library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
    dplyr::select(-row) %>%
    group_by(year) %>%
    mutate(new = str_c('col', row_number())) %>%  
    ungroup %>%  
    pivot_wider(names_from = new, values_from = int)
# A tibble: 2 x 6    
#   year  col1  col2  col3  col4  col5
#  <int> <int> <int> <int> <int> <int>
#1  2020   100   150   300   750   555
#2  2019   179   233   399   400   543

或使用data.tablerowid进行序列创建,可以将其传递到dcast的公式接口中>

library(data.table)
dcast(setDT(df1),  year ~ paste0('col', rowid(year)), value.var = 'int')

数据

df1 <- structure(list(row = 1:10, year = c(2020L, 2020L, 2020L, 2020L, 
2020L, 2019L, 2019L, 2019L, 2019L, 2019L), int = c(100L, 150L, 
300L, 750L, 555L, 179L, 233L, 399L, 400L, 543L)), 
class = "data.frame", row.names = c(NA, 
-10L))
© www.soinside.com 2019 - 2024. All rights reserved.