我有一个看起来像这样的数据框事件
EventCount Date
3317 2015-01-05
3388 2015-01-12
3467 2015-01-19
3455 2015-01-26
3506 2015-02-02
3561 2015-02-09
我想要的是根据活动发生的那一周创建一个新列' EventType' 2015-01-12之前发生的类型为A,2015-01-12和2015-02-02之间属于B类,2015-02-02之后属于C类。
我尝试使用ifelse条件创建新列。
Events$EventType<-ifelse(Events$Date < as.Date('2015-02-02'),"B","C")
这给了我一个新列,它只按两个条件进行分类,而不是三个。
答案 0 :(得分:2)
使用剪切
$companies = Company::where('is_client', '=', 1)
// load count on distant model
->with(['interactionSummaries.interaction' => function ($q) {
$q->withCount(['contactsAssociation' => function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Investor');
});
}]);
}])
->get()
->transform(function ($company) {
$company->contacts_association_count = $company->interactionSummaries
->pluck('interaction.contacts_association_count')
->collapse()
->sum();
return $company;
});
根据thelatemail
dt['EventType']=cut(dt$Date,breaks=as.Date(c('2000-01-01','2015-01-12','2015-02-02','2111-01-01')),labels = c('A','B','C'))
dt
EventCount Date EventType
1 3317 2015-01-05 A
2 3388 2015-01-12 B
3 3467 2015-01-19 B
4 3455 2015-01-26 B
5 3506 2015-02-02 C
6 3561 2015-02-09 C
答案 1 :(得分:0)
在实践中(也许是快点),您可以通过以下方式在两个命令中执行此操作:
Events$EventType <- ifelse(Events$Date < as.Date("2015-01-12"), "A", "B")
Events$EventType[Events$Date > "2015-02-02"] <- "C"
数据:
Events <- data.frame(EventCount = c(3317L, 3388L, 3467L, 3455L, 3506L, 3561L),
Date = c("2015-01-05", "2015-01-12", "2015-01-19",
"2015-01-26", "2015-02-02", "2015-02-09"))
Events$Date <- as.Date(Events$Date)
答案 2 :(得分:0)
这是我尝试使用sapply
的函数setEventType <- function(date){
if(date < as.Date("2015-01-12")){
return("A")
}
else if(date >= as.Date("2015-02-02")){
return("C")
}
else{
return("B")
}
}
Events$EventType <- sapply(as.Date(Events$Date), setEventType)
输出:
EventCount Date EventType
1 3317 2015-01-05 A
2 3388 2015-01-12 B
3 3467 2015-01-19 B
4 3455 2015-01-26 B
5 3506 2015-02-02 C
6 3561 2015-02-09 C