How to replace column values for cohort analysis

微笑、不失礼 提交于 2019-12-10 16:49:21

问题


I am very new to using R. I have searched regarding this but couldn't find any pointers.

I am doing cohort analysis and the data under Month1 is the number of new users that signed up for in that particular month. Month2 is the number of users that continued from previous month's sign up.

I have a set of data as follows

Month_Start_Date   Month1   Month2   Month3  Month4   Month5   Month6
2010-01-01           10        12       11      9       3        15
2010-02-01           10         9       11      9       3        15
2010-03-01           10         9        7      9       3        15
2010-04-01           10         7        5      6       3        15
2010-05-01           10         8        6      3       4        15

I would like my data to be in the following format:

Month_Start_Date   Month1   Month2   Month3  Month4   Month5   Month6
2010-01-01           10         0       0       0       0        0
2010-02-01           10         9       0       0       0        0
2010-03-01           10         9       7       0       0        0
2010-04-01           10         7       5       6       0        0
2010-05-01           10         8       6       3       4        0

My main data has data from 2008. I am filtering to take only from 2010. Hence, I would want the Month2, Month3, Month4, Month5 as 0 for 2010-01-01 and Month3, Month4, Month5 as 0 for 2010-02-01


回答1:


It seems like you want upper.tri to set the values to zero. Starting with

> df
#   Month_Start_Date Month1 Month2 Month3 Month4 Month5 Month6
# 1       2010-01-01     10     12     11      9      3     15
# 2       2010-02-01     10      9     11      9      3     15
# 3       2010-03-01     10      9      7      9      3     15
# 4       2010-04-01     10      7      5      6      3     15
# 5       2010-05-01     10      8      6      3      4     15

we can replace the upper triangle with zeros with

> df[-1][upper.tri(df[-1])] <- 0
> df
#   Month_Start_Date Month1 Month2 Month3 Month4 Month5 Month6
# 1       2010-01-01     10      0      0      0      0      0
# 2       2010-02-01     10      9      0      0      0      0
# 3       2010-03-01     10      9      7      0      0      0
# 4       2010-04-01     10      7      5      6      0      0
# 5       2010-05-01     10      8      6      3      4      0


来源:https://stackoverflow.com/questions/25857769/how-to-replace-column-values-for-cohort-analysis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!