尝试将函数包装到我的小巧创建代码周围

时间:2019-01-08 08:29:19

标签: r dataframe dplyr tibble

不带函数包装的代码可以满足要求,但是当我在函数周围包装函数时会返回NULL

根据建议,将两次复制的任何代码都转换为一个函数,我尝试根据我在程序中经常产生的小错误来制作一个函数。

但是当我将其放入函数中时,会返回NULL

# This works
for.gas <- tibble(Year = (start-1):(start+h-1))
for(i in countries){
  test.df           <- tibble(Year = (start-1):(start+h-1),
                              n    = NA
  )
  colnames(test.df) <- c("Year", paste(i))
  for.gas           <- left_join(for.gas, test.df)
}

# This doesn't
create.df <- function(df_name){
df_name <- tibble(Year = (start-1):(start+h-1))
for(i in countries){
  test.df           <- tibble(Year = (start-1):(start+h-1),
                              n    = NA
  )
  colnames(test.df) <- c("Year", paste(i))
  df_name           <- left_join(df_name, test.df)
}
}

# Expected results
# A tibble: 31 x 5
    Year Argentina Belgium Brazil Canada
   <int> <lgl>     <lgl>   <lgl>  <lgl> 
 1  2017 NA        NA      NA     NA    
 2  2018 NA        NA      NA     NA    
 3  2019 NA        NA      NA     NA    
 4  2020 NA        NA      NA     NA    
 5  2021 NA        NA      NA     NA    
 6  2022 NA        NA      NA     NA    
 7  2023 NA        NA      NA     NA    
 8  2024 NA        NA      NA     NA    
 9  2025 NA        NA      NA     NA    
10  2026 NA        NA      NA     NA    
# ... with 21 more rows

感谢所有帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

问题是发生了对'df_name'的赋值,但未进行return编辑

create.df <- function(df_name){
df_name <- tibble(Year = (start-1):(start+h-1))
for(i in countries){
  test.df           <- tibble(Year = (start-1):(start+h-1),
                              n    = NA
  )
     colnames(test.df) <- c("Year", paste(i))
     df_name           <- left_join(df_name, test.df)
     # assignment happened within the for loop
  }
 df_name  # note this step
 # or explicitly state to return (though not needed)
 # return(df_name) 
}

create.df(for.gas)