Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply user defined function across columns in R

Tags:

r

apply

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)
like image 431
Jack Armstrong Avatar asked Dec 09 '22 23:12

Jack Armstrong


2 Answers

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
like image 146
rjen Avatar answered Dec 30 '22 05:12

rjen


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)
like image 40
tpetzoldt Avatar answered Dec 30 '22 05:12

tpetzoldt