r:根据每个月的最大值编码虚拟变量

时间:2019-03-16 14:16:16

标签: r dplyr

我想基于每个df$dummydf$var1中的最大值编写一个名为df$month的新变量,其中最大值将为10表示其他所有值。查看可重复的数据集:

df<- data.frame(date= seq.Date(from = as.Date('2017-01-01'), by= 7, 
                length.out = 20), var1= rnorm(20, 5, 3))

df$month<- as.numeric(strftime(df$date, "%m"))

我很难在概念上说明该功能的条件。在Excel中,我只使用maxif函数并指定我的标准。我在下面的尝试无效:

df$dummy<- apply(df$var1, MARGIN = 2, 
                 function(x) if_else(max(x) %in% df$month, 1, 0))

它返回此错误:

Error in apply(df$var1, MARGIN = 2, function(x) if_else(max(x) %in% df$month,  : 
dim(X) must have a positive length

如何编码此虚拟变量?是否有使用dplyr的可行的mutate_if解决方案?

2 个答案:

答案 0 :(得分:1)

dplyr中,关键是使用group_by按月份分隔数据帧。然后,var1 == max(var1)将在每个月内根据需要运行。例如:

library(dplyr)
df<- data.frame(date= seq.Date(from = as.Date('2017-01-01'), by= 7, length.out = 20), var1= rnorm(20, 5, 3))
df$month<- as.numeric(strftime(df$date, "%m"))

df <- df %>%
  group_by(month) %>%
  mutate(dummy = as.integer(var1 == max(var1))) %>%
  ungroup

答案 1 :(得分:1)

使用data.table软件包很容易做到。

library(data.table)

df<- data.frame(date= seq.Date(from = as.Date('2017-01-01'), by= 7, 
                 length.out = 20), var1= rnorm(20, 5, 3))

df$month<- as.numeric(strftime(df$date, "%m"))

set.DT(df)
df[,dummy:=ifelse(max(var1)==var1,1,0),month]

## df
##           date      var1 month dummy
##  1: 2017-01-01  2.213981     1     0
##  2: 2017-01-08  1.768855     1     0
##  3: 2017-01-15  4.765936     1     0
##  4: 2017-01-22  3.930655     1     0
##  5: 2017-01-29  6.548077     1     1
##  6: 2017-02-05 -1.489263     2     0
##  7: 2017-02-12  4.448080     2     0
##  8: 2017-02-19  9.734254     2     1
##  9: 2017-02-26  3.322127     2     0
## 10: 2017-03-05  8.023423     3     1
## 11: 2017-03-12  6.915339     3     0
## 12: 2017-03-19  3.563988     3     0
## 13: 2017-03-26  4.393971     3     0
## 14: 2017-04-02  8.361803     4     0
## 15: 2017-04-09  3.636038     4     0
## 16: 2017-04-16  3.804143     4     0
## 17: 2017-04-23 11.269707     4     1
## 18: 2017-04-30  7.024666     4     0
## 19: 2017-05-07 10.771904     5     1
## 20: 2017-05-14  4.877943     5     0