2

我将如何多次运行它?

我有一个名为 percent_people 的变量,它查看变量国家/地区是否有 5000000 人,并且有一个名为 city_share 的变量查看每个城市的百分比份额,例如 London = 40%,百分比变量具有不同级别的多少他们可能会失业(即从 100% 到 75% 或 50% 或 25%),这些不同的百分比会如何影响失业率的变化?

但是,现在我只能引入一个 city_share 和一个 percent_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)
4

1 回答 1

3

我不确定这是否是您想要的,但如果您试图让函数一次接受多个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)
于 2020-05-07T14:12:35.360 回答