r - 函数的“for”循环
问题描述
我有以下数据集,其中包含 +7000 个城市,除以 21 个年龄段。列是“City”“City Code”(唯一)“Age Class”“N”和“D”。我必须为每个城市应用两个功能。我想知道是否可以编写一个for
循环来自动执行此操作。
数据集如下:
City City Code Class N D
...
Rome 5800 95 6633 1900
Milano 1500 0 5000 7
Milano 1500 1 21900 2
Milano 1500 5 28000 1
... ... ...
Milano 1500 90 12000 2000
Milano 1500 95 10000 1490
Venice 2700 0 742 3
...
对于每个城市,我必须执行以下程序:(
TOPALS_fit和e0是我之前提到的函数)
boundaries=c(0,1,seq(5,100,5))
N<-Milano$N
D<-Milano$D
names(N) = names(D) = head(boundaries,-1)
fit = TOPALS_fit(N,D,std,
age_group_bounds = boundaries,
details=TRUE)
h<-e0(fit$logm)
>h
[1] 85.27
(“fit”是 12 个列表,我对“logm”感兴趣)
问题是,对于每个城市,我都找到了一个值,我需要这样的输出:
City code City h
...
5800 Rome 84.5
1500 Milan 85.27
2700 Venice 84.38
...
我不知道是否可以通过循环或其他东西来做到这一点(?)任何帮助都会非常感激。
解决方案
这证明了这一点。for 循环遍历城市。您将获得带有 的城市列表unique(TotalDf[["City"]])
。代码被注释并解释了自己(我希望)。
请注意:为了使其可执行,我必须模拟一些变量和函数。
# Sample data
TotalDf <- read.table(header = TRUE, text = "
City CityCode Class N D
Rome 5800 95 6633 1900
Milano 1500 0 5000 7
Milano 1500 1 21900 2
Milano 1500 5 28000 1
Milano 1500 90 12000 2000
Milano 1500 95 10000 1490
Venice 2700 0 742 3")
# Mock function for demonstration purpose
TOPALS_fit <- function(N, D, std, age_group_bounds, details) {
return(list(alpha = NA, D = D, N = N, std = std, logm = runif(1)))
}
# Mock function for demonstration purpose
e0 <- function(x) x
# Mock variable for demonstration purpose
std <- NA
# Allocate memory
ResultDf <- data.frame(
CityCode = integer(length(unique(TotalDf[["City"]]))),
City = unique(TotalDf[["City"]]),
h = numeric(length(unique(TotalDf[["City"]])))
)
#
boundaries <- c(0,1,seq(5,100,5))
for (City in unique(TotalDf[["City"]])) {
# Subset data
Data <- TotalDf[TotalDf["City"] == City, ]
# Do your usual computations
N <- Data$N
D <- Data$D
# names(N) <- names(D) <- head(boundaries, -1) # omitted for demo purpose
fit = TOPALS_fit(N, D, std,
age_group_bounds = boundaries,
details=TRUE)
h <- e0(fit$logm)
# Put results into results data frame
CityCode <- unique(TotalDf[TotalDf["City"] == City, "CityCode"])
ResultDf[ResultDf[["City"]] == City, ] <- list(CityCode, City, h)
}
# Show result
ResultDf
#> CityCode City h
#> 1 5800 Rome 0.24561078
#> 2 1500 Milano 0.01275526
#> 3 2700 Venice 0.25215130
由reprex 包于 2021-04-26 创建 (v2.0.0 )
推荐阅读
- php - 通过 PHP 使用 imagemagick 向图像添加日期和时间?
- reactjs - React 客户端尝试访问服务器资源而不访问它得到 404
- node.js - 为运行二进制文件的 NPM 脚本设置 CWD
- webgl - 移除 TWGL 中的蓝色方块
- c# - 使用 DbDataReader 读取(迭代)数据时的巨大托管内存分配
- ios - 命令 RuleScriptExecution 失败,退出代码非零
- c# - Android游戏杆的问题
- ruby - 在 selenium webdriver + capyabara 中命名屏幕截图的好模式是什么
- c - 如何在应用程序包中找到 C 中的当前目录 [macOS]
- jquery - 使用 jQuery 删除导航类