I have two functions in R that convert a radian and an angle into Cartesian coordinates as follows:
x_cart<-function(theta,r){
  return(r * cos (theta))
}
y_cart<-function(theta,r){
  return(r * sin (theta))
}
Then I want to apply this function to create two new columns in my data frame as x and y from the columns angle and radius. When I use lapply, I get an error of argument r is missing with no default.
df$x<-apply(df[,c("angle_adj","hit_distance")],1, x_cart())
Test data
angle<-c(10,15,20)
radius<-c(15,35,10)
df<-data.frame(angle,radius)
                A tidyverse option.
library(dplyr)
df %>%
  mutate(X = x_cart(angle, radius),
         Y = y_cart(angle, radius))
#   angle radius          X         Y
# 1    10     15 -12.586073 -8.160317
# 2    15     35 -26.589077 22.760074
# 3    20     10   4.080821  9.129453
                        You don't need apply for this, use something like this:
x_cart<-function(theta,r){
  return(r * cos (theta))
}
y_cart<-function(theta,r){
  return(r * sin (theta))
}
angle<-c(10,15,20)
radius<-c(15,35,10)
df<-data.frame(angle,radius)
df$x <- x_cart(df$angle, df$radius)
# or using with()
df$x <- with(df, x_cart(angle, radius))
or even more compact:
cart <- function(theta,r){
  r * c(cos(theta), sin(theta))
}
df <- data.frame(
  angle = c(10, 15, 20),
  radius = c(15, 35, 10)
)
df[c("x", "y")] <- cart(df$angle, df$radius)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With