aba*_*ter 5 javascript python r dataframe pandas
在 R 中,您可以编写允许参数是预定义对象的不带引号的属性的函数。例如,DataFrame 对象的接口允许以下内容:
# df has columns "A" and "B"
df = mutate(df, C=A*B)
Run Code Online (Sandbox Code Playgroud)
现在df有一个新列“C”,它是“A”列和“B”列的乘积。
还有不加引号的“公式”类型:
lm(data=df, A~B)
Run Code Online (Sandbox Code Playgroud)
这种“非标准评价”。
是否可以在 Javascript 或 Python 中做类似的事情。
不,Python 和 JavaScript 中不可能有 NSE。
这是为什么?这是因为在 Python 和 JS 中,参数在传递给函数之前会被求值,而在 R 中则不然。
让我们考虑一下 R 和 Python 中的两个类似的代码:
enthusiastic_print <- function(x) {
print("Welcome!")
print(x)
}
enthusiastic_print("a" + 3)
Run Code Online (Sandbox Code Playgroud)
def enthusiastic_print(x):
print("Welcome!")
print(x)
}
enthusiastic_print("a" + 3)
Run Code Online (Sandbox Code Playgroud)
它们都会产生错误。但是现在,让我们看看错误发生的时间:
[1] "Welcome!"
Error in "a" + 3 : non-numeric argument to binary operator
exit status 1
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
File "main.py", line 6, in <module>
enthusiastic_print("a" + 3)
TypeError: can only concatenate str (not "int") to str
Run Code Online (Sandbox Code Playgroud)
您可以看到 Python 在调用之前评估传递给函数的内容。而 R 则保留作为参数传递的完整表达式,并仅在必要时对其求值。
您甚至可以在 R 中编写不会产生任何错误的代码:
foo <- function(x) {
print("Welcome in foo!")
print("I never mess with args...")
}
foo("a" + 3)
Run Code Online (Sandbox Code Playgroud)
您还可以捕获作为参数传递的内容而不对其求值:
verbatim_arg <- function(x) {
print(substitute(x))
}
verbatim_arg("a" + 3)
Run Code Online (Sandbox Code Playgroud)
其产生:
"a" + 3
Run Code Online (Sandbox Code Playgroud)
substitute()最后,这是允许eval()使用公式和所有其他 NSE 内容的函数。
你可以在node.js中做同样的测试
function enthusiastic_print(x) {
console.log("Welcome!")
console.log(x)
}
enthusiastic_print("a".notAMethod())
Run Code Online (Sandbox Code Playgroud)