我想重命名以相同字符串开头的多个列。 但是,我尝试的所有代码都没有更改列。
例如:
df %>% rename_at(vars(matches('^oldname,\\d+$')), ~ str_replace(., 'oldname', 'newname'))
还有这个:
df %>% rename_at(vars(starts_with(oldname)), funs(sub(oldname, newname, .))
您熟悉合适的重命名代码吗?
谢谢!
最佳答案
以iris
为例,您可以使用rename_with()
将那些以"Petal"
开头的列名替换为新字符串。
head(iris) %>%
rename_with(~ sub("^Petal", "New", .x), starts_with("Petal"))
Sepal.Length Sepal.Width New.Length New.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
在这种情况下,您还可以使用 rename_at()
,尽管 rename_if()
、rename_at()
和 rename_all( )
已被 rename_with()
取代。
head(iris) %>%
rename_at(vars(starts_with("Petal")), ~ sub("^Petal", "New", .x))
关于使用 r 中的 start with 重命名多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72144323/