我有一个包含每个客户每月收入的数据集:Underneath是一个有效的最小样本。 (真正的数据集运行多年,所有月份和多个客户端,但你得到了图片。)
client <-c("name1","name2","name3","name4","name5","name6")
Feb2018 <- c(10,11,NA,21,22,NA)
Jan2018 <- c(20,NA,NA,NA,58,NA)
Dec2017 <- c(30,23,33,NA,NA,NA)
Nov2017 <- c(40,22,75,NA,NA,11)
df <- data.frame(client,Feb2018,Jan2018,Dec2017,Nov2017)
我的目标是通过添加额外的列,将我们的收入分成“新”,“经常性”和“丢失”。
那是 :
- 新:客户在2018年有一些收入,但在2017年没有。(名称4和名称5)
- 经常性:客户在2017年和2018年有一些收入。(name1和name2)
- 丢失:客户在2017年有一些收入但在2018年没有。(名称3和名称6)
我知道如何使用grep来选择列名,
df[,c('client',colnames(df[grep('2018$',colnames(df))]))]
我也知道如何使用is.na.但我确实坚持在列名和选定列中存在NA的选择上进行组合。
看到我现在在圈子里思考几个小时了,我会感激一些帮助。谢谢阅读。
我们可以将gather
变成'long'格式然后应用条件然后再加入
library(dplyr)
library(tidyr)
df %>%
gather(key, val, -client, na.rm = TRUE) %>%
group_by(client) %>%
mutate(newcol = case_when(any(grepl('2018', key)) & all(!grepl('2017', key))~ 'new',
any(grepl('2018', key)) & any(grepl('2017', key)) ~ 'recurrent',
any(grepl('2017', key)) & all(!grepl('2018', key)) ~ 'lost')) %>%
distinct(client, newcol) %>%
right_join(df)
# A tibble: 6 x 6
# Groups: client [?]
# client newcol Feb2018 Jan2018 Dec2017 Nov2017
# <fctr> <chr> <dbl> <dbl> <dbl> <dbl>
#1 name1 recurrent 10.0 20.0 30.0 40.0
#2 name2 recurrent 11.0 NA 23.0 22.0
#3 name3 lost NA NA 33.0 75.0
#4 name4 new 21.0 NA NA NA
#5 name5 new 22.0 58.0 NA NA
#6 name6 lost NA NA NA 11.0