我想用函式更改資料框的列名。
為了用新的列名覆寫我的資料框,我使用了 assign(),它的第一個引數必須是與字串相同的資料框的名稱。為了將名稱作為字串獲取,我使用了 deparse(substitute(x)),它在函式外作業。但是在函式內部,它將我的資料框的內容作為字串而不是名稱本身回傳...
df <- data.frame(
emp_id = c (1:5),
emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
stringsAsFactors = FALSE
)
deparse(substitute(df))
rename_fun <- function(x) {
colnames(x)[1] <- "___0"
colnames(x)[2] <- "___1"
y <- deparse(substitute(x))
assign(y, x, envir = .GlobalEnv)
}
rename_fun(df)
我也試過
as.character(substitute(x))
但同樣的問題...
uj5u.com熱心網友回復:
另一種方法是使用as.character(match.call()$x)
,它可以在函式中的任何位置使用:
rename_fun <- function(x) {
colnames(x)[1] <- "___0"
colnames(x)[2] <- "___1"
assign(as.character(match.call()$x), x, envir = .GlobalEnv)
}
給予
rename_fun(df)
df
#> ___0 ___1
#> 1 1 Rick
#> 2 2 Dan
#> 3 3 Michelle
#> 4 4 Ryan
#> 5 5 Gary
請注意,不建議將物件寫入全域環境作為副作用的函式,即使它們正在覆寫現有物件。函式應回傳更改后的資料框,然后用戶可以選擇使用它來覆寫物件。
撰寫函式的更好方法是:
rename_fun <- function(x) {
colnames(x)[1] <- "___0"
colnames(x)[2] <- "___1"
x
}
哪個會這樣稱呼:
df <- rename_fun(df)
并給出相同的結果,同時如果呼叫者需要,則保留擁有原始資料幀副本的選項。
創建于 2022-11-18,使用reprex v2.0.2
uj5u.com熱心網友回復:
我們需要deparse/substitute
在函式的開頭使用
rename_fun <- function(x) {
y <- deparse(substitute(x))
colnames(x)[1] <- "___0"
colnames(x)[2] <- "___1"
assign(y, x, envir = .GlobalEnv)
}
-測驗
> rename_fun(df)
> df
___0 ___1
1 1 Rick
2 2 Dan
3 3 Michelle
4 4 Ryan
5 5 Gary
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/537598.html
標籤:r功能分配