species <- c("frog1","frog1","frog1","frog1","frog1","frog1","frog1","frog1"
,"frog1","frog1","frog2","frog2","frog2","frog2","frog2",
"frog2","frog2","frog2","frog2","frog2")
month <- c(1,12,5,8,10,3,5,7,9,4,2,4,6,7,6,3,8,9,11,1)
number <- c(3,4,5,1,2,3,4,7,6,7,3,5,6,7,8,9,9,5,3,1)
a<- data.frame(species,month,number)
我的数据框意味着我捕获了两种青蛙,frog1和frog2,不同月份的数字不同。
我想将月份转换为4个季节。第一季是第1个月,第12个月,第2个月,第二个是4,3,5,第三个是7,6,8,第四个是10,9,11。这四季有顺序,即第一季我想选择第1个月,第12个月,第2个月,第二个季节,同样地,在第二个季节我会先选择第4个月,第3个月第二个最终,第5个月,等等。例如,在青蛙1中,有2个月的1和12,我想在第一季中拿到第1个月而不是第12个月。
我想问一下如何创建一个可以在两种青蛙中依次为4个季节选择最重要月份的列。例如,在青蛙1中,有2个月1和12,我会喜欢在第一季中选择第1个月而不是第12个月。
我的预期输出是:
species <- c("frog1","frog1","frog1","frog1","frog1","frog1","frog1","frog1"
,"frog1","frog1","frog2","frog2","frog2","frog2","frog2",
"frog2","frog2","frog2","frog2","frog2")
month <- c(1,12,5,8,10,3,5,7,9,4,2,4,6,7,6,3,8,9,11,1)
number <- c(3,4,5,1,2,3,4,7,6,7,3,5,6,7,8,9,9,5,3,1)
choosemonth <- c("season1","","","","season4","","","season3","","season2",
"","season2","","season3","","","","season4","","season1")
b<- data.frame(species,month,number,choosemonth)
答案 0 :(得分:0)
我猜你最后想要的结果,但是这里是如何创造季节和重要性的,我正在解决每个物种最重要的月份
这是dplyr的一种方式:
library(dplyr)
a %>%
# Season is basically just one-off quarters
mutate(season = trunc((month + 1)%%12 / 3),
# for each month the value mod 3 goes in order 2,3,1
importance = c(2,3,1)[month %% 3 + 1]) %>%
group_by(season, species) %>%
# keep only those with the max importance
filter(importance == max(importance))
编辑:看起来你只想标记最重要的值,所以这里是如何做到的,
a %>%
# Season is basically just one-off quarters
mutate(season = trunc((month + 1)%%12 / 3),
# for each month the value mod 3 goes in order 2,3,1
importance = c(2,3,1)[month %% 3 + 1]) %>%
mutate(choosemonth = ifelse(importance == 3, paste0('season',season + 1),''))
编辑2:再编辑一次,分为3个季而不是4个季。