Thanks for all your helps.
I want to make macro with function
with R. In function
, there is long argument. This argument will not print
or return
specific value. But I want to make the results of arguments be reflected.
For example, I made some arguments with dplyr
The i
will be dataframe. I created the dataset test
set.seed(1001)
a<-rnorm(10)
b<-rnorm(10)
test<-data.frame(cbind(a,b))
test
Then I want to make column c
. The c
will be a
minus 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.
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
. Or since R by default returns the last line of the function, you can do
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.