我正在努力弄清楚如何才能展示2016年才发生的事件。该格式是chr格式,看起来类似于"2016-12-31“。是否有办法仅从2016年开始寻找价值?
当前代码:
most_fatalities_2016 <- gun_violence[which(gun_violence$date == "2016"), select = c("state", "city_or_county")]我想我正在寻找的r函数在SQL中的作用类似于类似的函数。有什么帮助吗?
发布于 2022-09-20 22:23:05
您可以简单地使用substr()或grepl()
gun_violence[substr(gun_violence$date,1,4)=="2016",]或
gun_violence[grepl("^2016-",gun_violence$date),]上面的内容返回gun_violence data.frame的所有列。如果只想返回特定的列,可以指定如下所示的列:
gun_violence[grepl("^2016-",gun_violence$date),c("state", "city_or_county")]发布于 2022-09-20 23:51:02
我可能比询问的内容更深入,但我想就数据的存储和操作方式给出一些建议。
如果我们事先将这个字符变量转换成适当的日期格式,那么下游分析就会容易得多。
建议2:
dplyr包为数据处理提供了非常清晰的语法,这可能是来自基于SQL的背景的一个很好的介绍。
建议3:
理解和“反向工程”的dbplyr包(https://dbplyr.tidyverse.org/)可能对SQL经验丰富的用户有启发作用。
gun_violence$date <-readr::parse_date(gun_violence$date)之后,我们可以使用许多与日期相关的函数,例如:
library(dplyr)
library(lubridate)
gun_violence %>% filter(date < today())
###
gun_violence %>% filter(year(date) == 2016) ### for the desired operation in the question
###
and so onhttps://stackoverflow.com/questions/73793145
复制相似问题