r - Move a column based in his colname after a column based in his colname in R
问题描述
I would like to be able to move columns to some desired position based solely on the name of the columns, I would like to move a column by name to the desired position after a column with a defined name.
You could use the data iris as an example.
Example:
data(iris)
Actual columns order:
> colnames(iris)
[1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
i would like to put "Petal.Width" after "Sepal.Length" by colnames using code and avoid putting manual inputs like selecting solutions with dplyr.
Thank you very much in advance.
解决方案
If I understand you correctly, you can achieve what you want using select, by manipulating the vector of column names.
First you need a function that takes a vector of names (assumed to be unique), and two specific entries a and b and move a behind b. I think this function does the trick (even if it is a little clumsy looking).
move <- function(names, a, b) {
names_without_a <- names[which(names != a)]
b_pos <- which(names_without_a == b)
c(names_without_a[1:b_pos],
a,
names_without_a[(b_pos+1):length(names_without_a)])
}
Now you can use select, like so
df <-
iris %>%
select(move(colnames(iris), 'Petal.Width', 'Sepal.Length'))
推荐阅读
- amazon-web-services - 如何使用 Terraform 更新 AWS ECS 集群实例?
- javascript - Promise all 中未捕获的异常
- python - 在 Python 中使用 time.sleep(),我想在同一行打印字符串
- excel - 尝试输入 nvarchar 参数以执行存储过程。出现 VBA 错误:运行时错误“3708”参数对象定义不正确
- azureservicebus - Azure 服务总线:如何在分区队列上启用强制消息排序?
- oauth-2.0 - 为什么认证成功后授权失败
- sql - SQL Server - 将分隔列数据透视到行中
- javascript - 为什么在尝试获取 onclick 事件时箭头函数在 JavaScript 中不起作用
- python - Python整数在循环中表现得很奇怪
- python-3.x - Python Selenium单击没有ID和名称的复选框