简体   繁体   English

如何通过替换R中的后缀来重命名列?

[英]How to rename columns by substituting suffix in R?

I have several column names in my dataset (eat10.18) that have the suffix "_10p."我的数据集 (eat10.18) 中有几个列名具有后缀“_10p”。 I'd like to change that suffix to be "_p_10" but preserve the rest of the variable name.我想将该后缀更改为“_p_10”,但保留变量名的其余部分。 I only want this to affect columns that end in the exact string "_10p."我只希望这会影响以确切字符串“_10p”结尾的列。 I cannot figure out how to make this work with rename_with().我无法弄清楚如何使用 rename_with() 来完成这项工作。 Can anyone help?任何人都可以帮忙吗? Faux data below:假数据如下:

eat10.18 <- data.frame(id = c(1000, 1001, 1002),
eat_10 = c(2, 4, 1),
eat_10p = c(1, 2, 3),
run_10p = c(1, 1, 2)) 

In the above example, the variables "id" and "eat_10" would remain the same, but "eat_10p" and "run_10p" would become "eat_p_10" and "run_p_10"在上面的示例中,变量“id”和“eat_10”将保持不变,但“eat_10p”和“run_10p”将变为“eat_p_10”和“run_p_10”

Thanks for your help!谢谢你的帮助!

library(tidyverse)

eat10.18 %>%
  rename_with(~str_replace(.,'_10p$', '_p_10'))

    id eat_10 eat_p_10 run_p_10
1 1000      2        1        1
2 1001      4        2        1
3 1002      1        3        2

I suggest using gsub and referring to this post .我建议使用gsub并参考这篇文章

names(eat10.18) <- gsub(x = names(eat10.18), pattern = "_10p", replacement = "_p_10")

Result结果

id ID eat_10吃_10 eat_p_10吃_p_10 run_p_10 run_p_10
1000 1000 2 2 1 1 1 1
1001 1001 4 4 2 2 1 1
1002 1002 1 1 3 3 2 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM