在R中跨列应用用户定义的函数
我在 R 中有两个函数可以将弧度和角度转换为笛卡尔坐标,如下所示:
x_cart<-function(theta,r){
return(r * cos (theta))
}
y_cart<-function(theta,r){
return(r * sin (theta))
}
然后我想应用这个函数在我的数据框中创建两个新列作为x和y从列angle和radius. 当我使用 lapply 时,我得到一个错误,参数 r is missing with no default。
df$x<-apply(df[,c("angle_adj","hit_distance")],1, x_cart())
测试数据
angle<-c(10,15,20)
radius<-c(15,35,10)
df<-data.frame(angle,radius)
回答
一个 tidyverse 选项。
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