在R中的天数中创建权属栏 [英] Creating a tenure column in Days in R

查看:58
本文介绍了在R中的天数中创建权属栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在df中创建一列,以向我显示客户任职期间的天数.这是为此创建模拟df的代码:-

I am trying to create a column in a df that shows me the day number in a client's tenure. Here is the code to create a mock df for this:-

     Date<-c("20/07/2018", "21/07/2018", "25/07/2018", "02/08/2018", "05/08/2018", "10/08/2018")
     ClientId<-c("aaa", "bbb", "ccc", "aaa", "bbb", "ccc")
     EventId<-c("klk109", "rrt234", "hjk786", "yyu777", "tyw909", "nnl991")
     dateclient<-cbind(Date, ClientId)
     LoginDates<-cbind(dateclient, EventId)
     View(LoginDates)

应该会给你这样的东西:-

which should give you something like this:-

   head(LoginDates)

      Date     ClientId  EventId 
  "20/07/2018" "aaa"    "klk109"
  "21/07/2018" "bbb"    "rrt234"
  "25/07/2018" "ccc"    "hjk786"
  "02/08/2018" "aaa"    "yyu777"
  "05/08/2018" "bbb"    "tyw909"
  "10/08/2018" "ccc"    "nnl991"

本质上,我想创建一列以这种方式添加到末尾

Essentialy, I want to create a column to add onto the end like this

     Date    ClientId  EventId   tenureDay
 "20/07/2018" "aaa"    "klk109"      1
 "21/07/2018" "bbb"    "rrt234"      1
 "25/07/2018" "ccc"    "hjk786"      1
 "02/08/2018" "aaa"    "yyu777"     13
 "05/08/2018" "bbb"    "tyw909"     15
 "10/08/2018" "ccc"    "nnl991"     16

但是,我数据集中的主要问题(上面是模拟df),有些客户每天有多个互动(有些有10个,20个,依此类推).我编写的代码("for"循环和一些data.table代码)返回了交互次数(或EventId),而不是任期中的天数.如果某个客户已经服务了10天,并且在这段时间内进行了4次互动,那么我希望tenureDay列代表其进行该特定互动的任期中的一天.

However, my main issue in my dataset (the above being a mock df), some Clients have had more than one interaction per day (some have had 10, 20 and so on). The code I wrote (a "for" loop and some data.table code) has returned the number of interactions (or EventIds), and not the day number in tenure. If a client has been in the service for 10 days and has had, say 4 interactions during that time, I want the tenureDay column to represent the day in their tenure that particular interaction took place on.

推荐答案

感谢您修改问题!

关于生殖力:

LoginDates <- fread("Date     ClientId  EventId 
                    2018-07-20 aaa    klk109
                    2018-07-21 bbb    rrt234
                    2018-07-25 ccc    hjk786
                    2018-08-02 aaa    yyu777
                    2018-08-05 bbb    tyw909
                    2018-08-10 ccc    nnl991")

使用 dplyr ,您可以尝试以下操作:

Using dplyr, you could try this:

LoginDates %>%
  group_by(ClientId) %>%
  mutate(tenureDay = as.Date(Date) - head(as.Date(Date),1))

我真的希望这能解决您的问题!

I really hope this solves your problem!

如果您不希望结果显示为 x Days ,请尝试:

If you do not want your result to appear like x Days then try:

LoginDates %>%
  group_by(ClientId) %>%
  mutate(tenureDay = as.numeric(as.Date(Date) - head(as.Date(Date),1)))

这篇关于在R中的天数中创建权属栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆