[英]R user defined functions: new data frame name as function parameter
我在編寫用戶定義的函數來操縱R中的數據框時遇到了一個問題。我想編寫帶有2個參數的函數:輸入數據框的名稱和將在該函數中創建的數據框的名稱。 這是使用mtcars數據集的示例:
subset_high_hp <- function(full_table, only_highHP) {
only_highHP <<- full_table %>%
filter(hp > 200)
}
subset_high_hp(mtcars, mtcars_highhp)
現在,subset_high_hp將創建一個名為only_highHP的數據框,而不是所需的mtcars_highhp。 我知道這是一個非常基本的問題,但是我是R語言的新手,確實很難找到正確的文檔。 誰能指出我正確的方向?
我認為您可以使用assign
來做到這一點:
subset_high_hp <- function(full_table, df_name) {
sub_df <- full_table %>%
filter(hp > 200)
assign(x = df_name, value = sub_df, envir = globalenv())
}
subset_high_hp(full_table = mtcars, df_name = "mtcars_highhp")
mtcars_highhp
mpg cyl disp hp drat wt qsec vs am gear carb
1 14.3 8 360 245 3.21 3.570 15.84 0 0 3 4
2 10.4 8 472 205 2.93 5.250 17.98 0 0 3 4
3 10.4 8 460 215 3.00 5.424 17.82 0 0 3 4
4 14.7 8 440 230 3.23 5.345 17.42 0 0 3 4
5 13.3 8 350 245 3.73 3.840 15.41 0 0 3 4
6 15.8 8 351 264 4.22 3.170 14.50 0 1 5 4
7 15.0 8 301 335 3.54 3.570 14.60 0 1 5 8
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.