我有一个31列的数据框。在Year列(名为“ Anos”)中,有重复的年份行,当我使用table(df $ Anos)时,得到的频率为年份。我只需要几年就可以进行12次观察(12个月)。
例:
freq_years <- table(df$Anos) freq_years Result: 2009 2010 2011 2012 2013 2014 2015 2017 2018 2019 2020 10 12 12 3 11 6 8 12 12 12 5
如何仅在freq = 12的年份自动获得新变量?(也许像2010,2011,2018,2019)
这是一个tidyverse
版本。根据您对数据框中其他30列的使用,将数据保持为df2
有用。
install.packages("dplyr")
install.packages("magrittr")
library("magrittr")
library("dplyr")
#create example dataset
df <- data.frame("Anos" = c(rep(2009,10),
rep(2010,12),
rep(2011,12),
rep(2012,3),
rep(2013,11),
rep(2014,6),
rep(2015,8),
rep(2016,12),
rep(2017,12)))
head(df)
# count number of years by row and filter to those with only 12
df2 <- df %>% group_by(Anos) %>% count() %>% filter(n == 12)
head(df2)
# create variable with list of years that have exactly 12 rows
variable <- df2$Anos
variable
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句