我如何运行多次?
我有一个名为percent_people的变量,它查看变量国家/地区是否有5000000人,并且有一个名为city_share的变量,它查看每个城市的百分比份额,例如伦敦= 40%,百分比变量具有不同级别的其中有多少人可能失业(即从 100% 到 75% 或 50% 或 25%),以及这些不同的百分比如何影响失业率的变化?
但是,现在我只能引入 1 个 city_share 和 1%_people 变量。我该如何编码才能循环遍历每个变量的多个输入?
现在我有以下内容:
library(dplyr)
Prediction <- function(city_share,
percent_people) {
unemployed_lon <-5000000 %>%
multiply_by(city_share) %>%
multiply_by(percent_people)
unemp <- 100000 +unemployed_lon
unemprate <- unemp %>% divide_by(5000000)
return(unemprate)
}
# Check -0.4 share + 100% percent_people
Prediction(0.4,1)
最佳答案
我不确定这是否是您想要的,但如果您试图让函数一次接受多个 percent_people
变量,您可以在函数内部循环它,以便它可以接受百分比向量:
library(dplyr)
library(magrittr)
Prediction <- function(city_share,
percent_people) {
unemprates <- c()
for (i in percent_people){
unemployed_lon <-5000000 %>%
multiply_by(city_share) %>%
multiply_by(percent_people)
unemp <- 100000 +unemployed_lon
unemprate <- unemp %>% divide_by(5000000)
}
return(unemprate)
}
# Check -0.4 share + 100% percent_people
Prediction(0.4,c(1,0.5,0.25))
Prediction(0.4,1)
如果您希望它也返回多个 city_share
输入的结果,我认为您可能需要切换到列表。下面的代码可能并不完美,但它可以为引入的每个 city_share 返回一个值列表。
library(dplyr)
library(magrittr)
Prediction <- function(city_share,
percent_people) {
unemprates_all<-list()
for (i in city_share){
unemp_share <- c()
for (j in percent_people){
unemployed_lon <-5000000 %>%
multiply_by(i) %>%
multiply_by(j)
unemp <- 100000 + unemployed_lon
unemp <- unemp %>% divide_by(5000000)
unemp_share <- append(unemp_share,unemp)
}
unemprate <- list(unemp_share)
unemprates_all[[length(unemprates_all)+1]] <- unemprate
}
return(unemprates_all)
}
# Check -0.4 share + 100% percent_people
Prediction(c(0.4,0.2),c(1,0.5))
Prediction(0.4,1)
关于r - 如何获得对观察运行函数的多个结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61659323/