[英]How do I make a function that returns the equation from the argument?
例如,我有一個 function 和 arguments “x”、“d”和“方程”。 “x”參數是我的數據框,“d”參數是數字數據框列,在“方程式”參數中我想插入方程式“d * 5 ^ 0.02”。
作為 output,我需要在數據框中添加一個新列“V”,其中包含參數方程的結果。
我的想法錯了:
myfunction <- function(x, d, equation, ...){
x$V <- equation
}
myfunction(x=x, d = x$d, equation = c("d"*5^0.02))
你有這樣的想法嗎?
myfunction <- function(x, d, equation, ...) x$v <<- eval(substitute(equation))
x <- data.frame(d = 1:5)
myfunction(x=x, d = x$d, equation = d*5^0.02)
x
#> d v
#> 1 1 1.032712
#> 2 2 2.065425
#> 3 3 3.098137
#> 4 4 4.130850
#> 5 5 5.163562
思考了一下之后,我想知道您是否正在嘗試在within
進行改造?
within(x, v <- d*5^0.02)
#> d v
#> 1 1 1.032712
#> 2 2 2.065425
#> 3 3 3.098137
#> 4 4 4.130850
#> 5 5 5.163562
由代表 package (v0.3.0) 於 2020 年 5 月 27 日創建
我假設您希望將equation
應用於x$d
,並將結果寫入x$V
。
提供這樣的“方程式”是非常不尋常的,並且容易出錯。 考慮創建一個 function: f <- function(x) x * 5^0.02
,然后執行以下操作。
# dummy data
x <- data.frame(d = 1:10)
# your equation
f <- function(x) x * 5^0.02
g <- function(x, d, f) {
# call function f with column d as its argument
x$V <- f(x[[d]]))
return(x)
}
g(x, "d", f)
d V
1 1 1.032712
2 2 2.065425
3 3 3.098137
4 4 4.130850
5 5 5.163562
與其他答案類似。 但是,在副作用中運行的函數會排除以下情況:分配給新變量(一個答案建議一種方法來執行此操作),或在管道中運行(例如, %>%
)。
我建議不要使用副作用( <<-
和assign
)。
myfunction <- function(x, d, equation, ...) {
x$V <- eval(substitute(equation), envir = x)
x
}
x <- data.frame(d = 1:5)
myfunction(x, x$d, d*5^0.02)
# d V
# 1 1 1.032712
# 2 2 2.065425
# 3 3 3.098137
# 4 4 4.130850
# 5 5 5.163562
原始x
不變。 使用功能性副副作用范例的一個優點是它會在(比如說)管道中更好地流動:
library(dplyr)
x %>%
myfunction(d, d*5^0.02)
# d V
# 1 1 1.032712
# 2 2 2.065425
# 3 3 3.098137
# 4 4 4.130850
# 5 5 5.163562
而使用副作用可能不會影響預期/期望的x
。
x %>%
filter(between(d, 2, 4)) %>%
myfunction(d, d*5^0.02)
# d V
# 1 2 2.065425
# 2 3 3.098137
# 3 4 4.13085
(這在使用副作用時不起作用。)
或者,我們已經在基礎 R 中有一個 function :
within(x, { V = d*5^0.02 })
# d V
# 1 1 1.032712
# 2 2 2.065425
# 3 3 3.098137
# 4 4 4.130850
# 5 5 5.163562
transform(x, V = d*5^0.02 )
# d V
# 1 1 1.032712
# 2 2 2.065425
# 3 3 3.098137
# 4 4 4.130850
# 5 5 5.163562
這里可以直接返回全局環境:
x <- data.frame(c(1:2,5:6),c(7:10))
x
colnames(x) <- c("V1","d")
myfunction <- function(x, d, equation,named.df="NA" ,...){
x$V <- equation
assign(named.df,x, envir=.GlobalEnv)
}
myfunction(x=x, d = x$d, equation = c(x$d*5^0.02),"function result" )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.