R中如何实现向量或时间序列按任意角度旋转的代码示例
二维向量任意角度旋转实现(R语言)
实现思路
采用标准二维刚性旋转逻辑,全程保持所有点的相对距离不变,自动满足首尾点约束要求:
- 先将所有点的坐标平移到「旋转中心为原点」的相对坐标系
- 套用旋转矩阵计算旋转后的相对坐标
- 将坐标平移回原坐标系,得到最终输出向量
可复用旋转函数
rotate_2d <- function(x, y, angle_deg, center = NULL) { # 角度转弧度 theta <- angle_deg * pi / 180 # 默认取所有点的质心为旋转中心 if (is.null(center)) { cx <- mean(x) cy <- mean(y) } else { cx <- center[1] cy <- center[2] } # 平移到相对坐标系 x_rel <- x - cx y_rel <- y - cy # 旋转矩阵计算 x_rot <- x_rel * cos(theta) - y_rel * sin(theta) y_rot <- x_rel * sin(theta) + y_rel * cos(theta) # 平移回原坐标系 x_new <- x_rot + cx y_new <- y_rot + cy return(list(x_rot = x_new, y_rot = y_new)) }
针对示例向量的运行示例
直接使用给出的输入向量测试:
# 原始输入向量 y <- c(1,7,4,8,4,6,1) x <- c(1,2,3,4,5,6,7) # 调用函数旋转30度(逆时针为正,顺时针可填负数) rotated <- rotate_2d(x = x, y = y, angle_deg = 30) # 提取旋转后的输出向量 x_rotated <- rotated$x_rot y_rotated <- rotated$y_rot # 查看输出结果 x_rotated y_rotated
效果验证(可选绘图代码)
可直接用基础绘图函数直观对比旋转前后的折线形态,无需安装额外依赖包:
# 绘制适配全范围的空白画布 plot(range(c(x, x_rotated)), range(c(y, y_rotated)), type = "n", xlab = "x", ylab = "y", main = "旋转前后对比") # 绘制原始折线 lines(x, y, col = "gray50", lwd = 2) # 绘制旋转后的折线 lines(x_rotated, y_rotated, col = "red", lwd = 2) legend("topright", legend = c("原始向量", "旋转后向量"), col = c("gray50", "red"), lwd = 2)
自定义参数说明
- 旋转中心可通过
center参数手动指定,比如要绕序列第一个点旋转,直接传center = c(x[1], y[1])即可 - 角度单位为度,支持正负值:逆时针旋转填正数,顺时针旋转填负数
- 输出为列表结构,分别对应旋转后的x、y向量,可直接提取用于后续计算
内容的提问来源于stack exchange,提问作者mr.T
相关产品推荐
相关产品推荐

