我如何在R中将数据按普通年份行排列到单独的列中?

我如何在R中将数据按普通年份行排列到单独的列中?,r,R,我对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

我对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或base R。谢谢你,

我们可以按“年”创建序列列,然后转向“宽”格式

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
数据
df1再次感谢@akrun,这非常有帮助,使用tidyverse工作非常完美。你能告诉我最后一步吗,完成后如何删除“年”列?我尝试了'select(df1,-Year)`但它保留了Year列。@JacksonWalker有一个group属性,我用
ungroup
删除了它,现在,它应该可以与
select
@akrun一起使用了。
dplyr::select(-row)
的目的是什么?我收到以下错误
“此tidyselect接口尚不支持谓词。”
此外,我可以删除该行而不影响输出。@sachin2014不需要列“row”,因此通过
选择将其删除。无法重现那个错误
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))