[英]R - How to add the sum of a specific occurrence in one column to another column
Using R. 使用R。
This is a small subset of my dataset, simplified to only show relevant columns. 这是我的数据集的一小部分,简化为仅显示相关列。 The data is taken from Capital Bikeshare.
数据取自Capital Bikeshare。 The Start.Date column below has exact rental times for a bike.
下面的Start.Date列具有自行车的确切租赁时间。
Start.date Member.type
2018-11-01 00:00:45 Member
2018-11-01 00:00:52 Casual
2018-11-01 00:01:46 Member
2018-11-01 01:00:02 Casual
2018-11-01 01:03:36 Member
What I'm trying to do is group all of the data by date, hour of day, number of each member type, and total number of member types (casual+member) for any given hour of any given day. 我想做的是将所有数据按日期,一天中的小时,每种成员类型的数量以及任意一天中任何给定小时的成员类型总数(休闲+成员)进行分组。 So, in the end, I'll just have "Day - Hour - Number of Rentals per member type" so I can predict trends for hour of the day,
因此,最后,我将只有“天-小时-每个成员类型的租车数量”,这样我就可以预测一天中每小时的趋势,
Here is my relevant code 这是我的相关代码
library(dplyr)
bikeData <- read.csv("2011data.csv")
bikeData <- bikeData %>%
mutate(Hour = format(strptime(
bikeData$Start.date, "%Y-%m-%d %H:%M:%S"), "%m-%d %H")) %>%
mutate(day = wday(Start.date, label=TRUE))
groupData <- bikeData %>%
mutate(Start.date = ymd_hms(Start.date)) %>%
count(date1 = as.Date(Start.date), Hour1 = hour(Start.date),
member=(Member.type)) %>%
group_by(date1, Hour1) %>%
arrange(date1, Hour1) %>%
summarise(total=sum(n))
What this gives me is the following new dataset, groupData 这给了我以下新的数据集groupData
date1 Hour1 total
2018-11-01 0 82
2018-11-01 1 43
2018-11-01 2 17
2018-11-01 3 4
2018-11-02 0 5
2018-11-02 1 24
So I was able to do the total number of Member+Casual for all 24 hours of each day of my dataset, but how do I get another two columns that show the total number of casual and another that shows the total number of member? 这样我就可以计算出数据集每天24小时内的Member + Casual总数,但是如何获得另外两列显示Casual总数的列和另一列显示Member总数的列? Thanks!
谢谢!
Desired below: 需要以下内容:
date1 Hour1 total Casual Member
2018-11-01 0 82 40 42
2018-11-01 1 43 20 23
2018-11-01 2 17 10 7
2018-11-01 3 4 1 3
2018-11-02 0 5 1 4
2018-11-02 1 24 20 4
groupData <- bikeData %>%
mutate(Start.date = ymd_hms(Start.date)) %>%
count(date1 = as.Date(Start.date), Hour1 = hour(Start.date),
member=(Member.type)) %>%
group_by(date1, Hour1) %>%
arrange(date1, Hour1) %>%
summarise(total=sum(n),members=sum(Member.type=="Member"),casuals=sum(Member.type=="Casual"))
You can simply add to your summarize call two variables that count the logical occurrences of Member.type equaling each of the options. 您可以简单地将两个变量添加到摘要调用中,这两个变量计算Member.type的逻辑出现次数(等于每个选项)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.