【问题标题】:How can I manipulate this data with using for loops in R如何在 R 中使用 for 循环来操作这些数据
【发布时间】:2019-06-12 12:36:46
【问题描述】:

我在处理 R 中的数据时遇到问题。我在这项工作中需要的是通过链接中的示例数据来操作数据。当我尝试这样做时,我尝试使用 dplyr 包,但它没有用。所以我想用for循环来做。

我想要的正是这个:

我想保持 A、B、C、D、E 类别固定,并将其旁边月份的数据放在一起。像 1990 年 1 月、1990 年 2 月、....、1990 年 12 月、1991 年 1 月、1991 年 2 月、...、1991 年 12 月。这些月份将并排并以列的形式出现。由于某些年份没有特定类别的数据,因此应在与这些类​​别对应的月份中给出“0”值。我应该如何为此编写一个 for 循环?

提前感谢您的帮助。

【问题讨论】:

  • 请提供您的数据dput 而不是图片。
  • 请以可重现的方式提供您的数据,例如执行dput(data) 并粘贴结果。如果太长,可以试试dput(head(data))
  • 你是说你只想要 5 行,然后每个月/年组合的列?如果是这样,我实际上会避免使用 forloop 并继续使用 dplyr。您可以在数据上使用dplyr::gather 来获得 4 列:年份、类别、月份和数据值。然后您可以使用mutate 创建一个新变量dplyr::mutate(year_month = paste0(year,"-",month)),然后使用dplyr::spread 获得您要查找的输出。

标签: r dplyr


【解决方案1】:

使用你的照片的假冒我写了以下内容。让我知道输出是否为 ac 这类似于 rfortin 的建议,但使用 data.table 而不是 dplyr

代码:

library(data.table)

dt <- melt(data, id.vars = c("Year", "Category"), measure.vars = c("Jan", "Feb"), 
           variable.name = "Month", value.name = "Profit") %>%
  .[, `Month-Year`:= paste(`Month`, `Year`, sep = " ")] %>%
  dcast(., `Category` ~ `Month-Year`, fun.aggregate = sum, value.var = "Profit")

数据:

data <- data.table(Year = c(1999,1999,1999,2000,2000,2000,2001,2001,2001), 
                   Category = c("A", "B", "C","A", "B", "C","A", "B", "C"), 
                   Jan = c(234234,3413,134,134,13423,1324,1324,1235,54), 
                   Feb = c(234523,435234,0,2342,0,153,24,234,72))

输出:

   Category Feb 1999 Feb 2000 Feb 2001 Jan 1999 Jan 2000 Jan 2001
1:        A   234523     2342       24   234234      134     1324
2:        B   435234        0      234     3413    13423     1235
3:        C        0      153       72      134     1324       54

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 2021-10-31
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多