问题描述
我有年,月,商品和数量的贸易数据。我想创建每种商品,每月,每年的总量 x_total ,并将其显示为新变量,并且该组中每个观察值的编号都相同
例如:
我所拥有的:
"Kestrel": {
"EndpointDefaults": {
"Protocols": "Http1"
}
}
我想看的是:
"iisSettings": {
"windowsAuthentication": false,"anonymousAuthentication": true,"iisExpress": {
"applicationUrl": "http://localhost:55974","sslPort": 44318
}
},"profiles": {
"IIS Express": {
"commandName": "IISExpress","launchBrowser": true,"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}","environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},"BlazorClientDemoApp": {
"commandName": "Project","applicationUrl": "https://localhost:5001;http://localhost:5000","environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
到目前为止,我的代码如下:
Windows 8.1 64bit
VisualStudio 2019: 16.7.6 version,SDK 3.1.403 Core,Microsoft .NET Framework Wersja 4.8.03761,ASP.NET and Web Tools 2019 16.7.532.,ASP.NET Core Razor Language Services 16.1.0.,ASP.NET Web Frameworks and Tools 2019 16.7.532.28833
我一直在使用 mutate 创建以前的变量。
我希望保留 X_Quantity 变量,以将每个商品的数量除以 X_total 最终创建一个 X_share 变量。
我希望这是有道理的,请原谅我犯的任何发帖错误(这是我的第一篇帖子)。
非常感谢。
解决方法
尝试一下。您需要按Year
和Month
分组才能获得预期的输出。这里的代码:
library(dplyr)
#Code
newdf <- Totals %>% group_by(Year,Month) %>% mutate(X_total=sum(X_Quantity),X_share=X_Quantity/X_total)
输出:
# A tibble: 4 x 6
# Groups: Year,Month [2]
Year Month Commodity X_Quantity X_total X_share
<int> <int> <chr> <int> <int> <dbl>
1 2010 1 apples 10 15 0.667
2 2010 1 bananas 5 15 0.333
3 2010 2 apples 9 13 0.692
4 2010 2 bananas 4 13 0.308
使用了一些数据:
#Data
Totals <- structure(list(Year = c(2010L,2010L,2010L),Month = c(1L,1L,2L,2L),Commodity = c("apples","bananas","apples","bananas"
),X_Quantity = c(10L,5L,9L,4L)),class = "data.frame",row.names = c(NA,-4L))