【问题标题】:The output of dput(head(data, 20)) in data frame in RR中数据帧中dput(head(data,20))的输出
【发布时间】:2021-06-17 20:30:42
【问题描述】:

我有一个如下数据集(名称:数据),其中包括多个国家/地区,在 3 列和 251453 行中的不同日期具有多种事件类型。我想计算每个国家/地区的每月事件。比如我想看“八月”中“也门”的“战斗”数量?我总共有 6 种不同的事件类型和 8 个不同的国家/地区。

尽管花费了几个小时,但还是没有任何进展。感谢任何指导。

|event_date|        |event_type|                |country|
12 March 2021   Explosions/Remote violence;     Yemen;
12 March 2021   Explosions/Remote violence      Yemen
12 March 2021   Battles                         Afghanistan;
12 March 2021   Battles                         Afghanistan
12 March 2021   Protests                        Yemen 
12 March 2021   Protests                        Yemen

dput(样本)的输出

dput(head(data, 20))
structure(list(event_date = structure(c(420L, 420L, 420L, 420L, 
420L, 420L, 420L, 420L, 420L, 420L, 420L, 420L, 420L, 420L, 420L, 
420L, 420L, 420L, 420L, 420L), .Label = c("01 April 2018", "01 April 2019", 
"01 April 2020", "01 August 2018", "01 August 2019", "01 August 2020", 
"01 December 2018", "01 December 2019", "01 December 2020", "01 February 2019", 
    event_type = structure(c(2L, 2L, 1L, 1L, 3L, 3L, 3L, 3L, 
    4L, 1L, 1L, 3L, 4L, 3L, 1L, 1L, 4L, 6L, 6L, 3L), .Label = c("Battles", 
    "Explosions/Remote violence", "Protests", "Riots", "Strategic developments", 
    "Violence against civilians"), class = "factor"), country = structure(c(8L, 
    8L, 1L, 1L, 8L, 8L, 3L, 5L, 8L, 8L, 8L, 5L, 5L, 5L, 1L, 1L, 
    5L, 8L, 8L, 4L), .Label = c("Afghanistan", "Colombia", "India", 
    "Iraq", "Lebanon", "Libya", "Mali", "Yemen"), class = "factor")), row.names = c(NA, 
20L), class = "data.frame")
  

【问题讨论】:

  • 您已经尝试过什么,您在哪个部分遇到了问题?多少部分?八月部分?也门部分?
  • @RobinGertenbach 非常感谢您的关注。我是 R 的初学者,所以我首先尝试将 event_date 变量转换为日期,因为它是因素,然后尝试按国家/地区计算每个月的事件类型。但无济于事......我只想计算每个国家/地区的每月事件类型!非常感谢...
  • 您能以dput 格式发布示例数据吗?请使用dput(head(mydata, 20)) 的输出编辑问题
  • @RuiBarradas 非常感谢 Rui,我已经包含了样本数据的 dput 输出。对此表示赞赏。
  • 感谢提供数据,但dput 的输出似乎没有很好地发布,请您重新发布吗?

标签: r lubridate counting


【解决方案1】:

只要日期是实际日期,就可以使用aggregate 完成。

首先,将event_date 列强制转换为"Date" 类。

data$event_date <- as.Date(data$event_date, format = "%d %B %Y")

现在,这里有两种方法,第一种不考虑年份按月计算,第二种按年和月计算。

month <- format(data$event_date, "%B")
aggregate(event_type ~ month + country, data, length)

yearmonth <- format(data$event_date, "%Y %B")
aggregate(event_type ~ yearmonth + country, data, length)

【讨论】:

  • 感谢您的时间和支持。它有效
猜你喜欢
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 2013-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多