gpt4 book ai didi

r - 分布在 R 中的多个列 - dplyr tidyr 解决方案

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

我有一个长格式的月度同比数据,我试图用两列传播。我见过的唯一示例包括单个 key

> dput(df)
structure(list(ID = c("a", "a", "a", "a", "a", "a", "a", "a",
"a", "b", "b", "b", "b", "b", "b", "b", "b", "b"), Year = c(2015L,
2015L, 2015L, 2016L, 2016L, 2016L, 2017L, 2017L, 2017L, 2015L,
2015L, 2015L, 2016L, 2016L, 2016L, 2017L, 2017L, 2017L), Month = c(1L,
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L,
3L), Value = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 6L, 7L, 8L,
9L, 10L, 11L, 12L, 13L, 14L)), .Names = c("ID", "Year", "Month",
"Value"), class = "data.frame", row.names = c(NA, -18L))

我试图将其转换成一种数据格式,其中年份为 2:5 列,每个 month 每个 ID

一行
ID  Month   2015    2016    2017
a 1 1 2 3
a 2 1 2 3
a 3 1 2 3
a 1 6 9 12
a 2 7 10 13
a 3 8 11 14

我试过以下错误:

by_month_over_years = spread(df,key = c(Year,Month), Value)
Error: `var` must evaluate to a single number or a column name, not an integer vector

最佳答案

library(tidyr)
library(dplyr)
df %>% group_by(ID) %>% spread(Year, Value)

# A tibble: 6 x 5
# Groups: ID [2]
ID Month `2015` `2016` `2017`
<chr> <int> <int> <int> <int>
1 a 1 1 2 3
2 a 2 1 2 3
3 a 3 1 2 3
4 b 1 6 9 12
5 b 2 7 10 13
6 b 3 8 11 14

关于r - 分布在 R 中的多个列 - dplyr tidyr 解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51846611/

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