Passing and returning functions in R

Outlier

I want to create a function in R, which take data as a function, do some operation on it(add some columns/Rows etc) and return it. I found usually I can not do so.

f <- function(d = cars){
    d$new = ifelse(d$dist > rep(10, nrow(d)), 1, 0)
    return d 
}

Error: unexpected symbol in:
"d$new= ifelse(d$dist>rep(10,nrow(d)),1,0)
return d"

If I remove return d, I get only the vector, not whole data frame.
Any suggestion?

MrFlick

Functions in R return the value from the last statement executed. When you do an assignment, the value from the left side of the assignment is the (invisibly) returned result. For exampel

d <- cars
a <- (d$new <- ifelse(d$dist>10, 1, 0))
a

#  [1] 0 0 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
# [40] 1 1 1 1 1 1 1 1 1 1 1

So in your example you're merely returning the vector you just created. R doesn't know that you want to return the whole d data.frame. If you put the return(d), it will know that's what you want. You can even just put d on the last line by itself to return that value.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Passing labels to selectize and returning values for server functions

Passing structs to functions and returning structs from functions in Zig

R functions: passing arguments with ellipsis

Passing in unbound variables into R functions

Passing a list of functions to ddply in R

Passing and returning structs to C functions on stack from Common Lisp with CFFI

Passing chords to and returning music with Lilypond music substitution functions

returning functions in R - when does the binding occur?

Problem passing arguments to called functions in R

R: passing values to eval in nested functions

R: On scoping, passing arguments to interior functions, and

Passing R functions to C routines using rcpp

R passing missing arguments through functions

Basics of argument passing in R's functions

Passing results of different functions to a function the R way

Argument passing in R to functions of several real variables

Passing values between functions in an R package

Passing vectors and params from Python to R functions

Passing arbitrary arguments to multiple nested functions in R

R: passing one value to a vector of functions

MD5 file hash functions in R returning different values?

struct function passing and returning

returning a vector or passing by reference

passing and returning useState in react

Passing multiple variable information inside R functions using string variable

errors when passing multiple arguments to dplyr functions in R

R tidyeval passing a list containing multiple character vectors to dplyr functions

Passing arguments in R within functions, error unused arguments

Trouble passing in variable names for R user defined functions