Home > other >  Passing data frame data through function
Passing data frame data through function

Time:12-21

# mtcars <- view(mtcars)

sq_sum_diff <- function(d, w) {  # d, and c are columns draft and weight
  a <- d^2
  b <- w^2
  p <- sqrt(sum(a^2 - b^2)
  return(p)
}

What I want returned is a df with the difference in squares between the two.

CodePudding user response:

I think this will do what you're trying to accomplish:

data(mtcars)

sq_sum_diff <- function(d, w) {
  sqrt(sum(d^2 - w^2))
}
sq_sum_diff(mtcars$drat, mtcars$wt)

Why are you squaring the values twice? Once when you assign d^2 to a and again when you calculate the sum of squares? Also, you're missing the matching parenthesis of sqrt. Lastly, you don't need to assign to p and then return(p), the function will automatically return the last line. And for future reference, you can simply call data(mtcars) without assigning it to mtcars.

  • Related