[英]How to make long argument in function reflected in R
Thanks for all your helps.感谢您的所有帮助。
I want to make macro with function
with R. In function
, there is long argument.我想用 R 制作带有
function
宏。在function
,有很长的参数。 This argument will not print
or return
specific value.此参数不会
print
或return
特定值。 But I want to make the results of arguments be reflected.但我想让争论的结果得到反映。
For example, I made some arguments with dplyr
例如,我与
dplyr
进行了一些争论
The i
will be dataframe. i
将是数据框。 I created the dataset test
我创建了数据集
test
set.seed(1001)
a<-rnorm(10)
b<-rnorm(10)
test<-data.frame(cbind(a,b))
test
Then I want to make column c
.然后我想制作列
c
。 The c
will be a
minus b
c
将是a
减b
fun<-function(i){
i<-i%>%mutate(c=a-b)}
fun(i=test)
But, when i checked the test
, the c
variable was not generated.但是,当我检查
test
,没有生成c
变量。
How to make the results of arguments in function reflected?如何让函数中参数的结果体现出来?
You need to add return
in the function and assign the value back to test
.您需要在函数中添加
return
并将值分配回test
。 Or since R by default returns the last line of the function, you can do或者因为 R 默认返回函数的最后一行,你可以这样做
library(dplyr)
fun <- function(i) i %>% mutate(c = a - b)
test <- fun(test)
test
# a b c
#1 2.189 0.303 1.886
#2 -0.178 1.634 -1.812
#3 -0.185 -0.622 0.437
#4 -2.507 0.467 -2.974
#5 -0.557 1.419 -1.977
#6 -0.144 0.110 -0.254
#7 1.092 1.870 -0.778
#8 -0.623 -1.030 0.407
#9 -0.907 -1.342 0.434
#10 -1.594 0.554 -2.148
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.