-2
# 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.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Toy L
  • 55
  • 6
  • 1
    `d <- data.frame( d=with( mtcars, sq_sum_diff( draft, weight) ))`. And do test your code in the future before displaying your efforts to the world on StackOverflow. You have a missing parenthesis. (Maybe you meant `drat`?) – IRTFM Dec 19 '21 at 00:47
  • 1
    You don't need to use `return()` when you are just returning the last line. Are you saying you want to return a single column data frame with a^2-b^2 (i.e d^4 - w^4)? Or do you want to add a new column to the existing data frame? – Elin Dec 19 '21 at 02:33
  • @IRTFM,Sorry for the typo. Looking back it was a copy and paste issue. Sorry. – Toy L Dec 20 '21 at 21:15
  • @Elin, yes, you are correct in your 1st question. I think if I wanted to do that, however, I need to remove the `sum` function right? Also, thank you for the correction about the 'return()'. I am still new to coding, so any correction helps. – Toy L Dec 20 '21 at 21:17

1 Answers1

1

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)


library(tidyverse)

mtcars %>% 
  summarize(dif_sqr = sq_sum_diff(drat, 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.

Andrew
  • 490
  • 3
  • 9
  • Hey, thank you for the response! I figured that part out already. Since I have posted this, I have removed the `sum` function, ran the code, and got a 31 rows of data. I think I can turn that into a `df`. – Toy L Dec 20 '21 at 21:25
  • 1
    I missed the part about wanting a data.frame. I added a bit of code to my answer that would produce a data frame with a single column for difference of squares if that's helpful. – Andrew Dec 21 '21 at 23:23