如何使用字符对象将r在r中重命名列?

发布于 2025-02-13 18:44:02 字数 785 浏览 2 评论 0原文

我的数据框架就是这样:

#generic dataset
datatest <- data.frame(col1 = c(1,2,3,4), col2 = c('A', 'B', 'C', 'D'))

#character objects
name1 <- 'A'
name2 <- 'B'

我想使用name1和name2对象重命名列。这些动态更改代码,因此我无法使用以下内容:

#I DON'T WANT THIS
datatest %>% rename(A = col1, B = col2)

我想使用以下内容:

datatest %>% rename(name1 = col1, name2 = col2)

但是,数据表列最终分别成为'name1'和'name2',当它们应为a和B时。这是目前的数据表。

name1(我希望这是a)name2(我希望这是b)
1A
2B
3C
4D

任何帮助都非常感谢。我也在Kable桌子上也有同样的问题。 提前致谢!

My data frame is as such:

#generic dataset
datatest <- data.frame(col1 = c(1,2,3,4), col2 = c('A', 'B', 'C', 'D'))

#character objects
name1 <- 'A'
name2 <- 'B'

I want to rename my columns using the name1 and name2 objects. These dynamically change in the code so I can't use the following:

#I DON'T WANT THIS
datatest %>% rename(A = col1, B = col2)

I want to use this:

datatest %>% rename(name1 = col1, name2 = col2)

but then the data table columns end up becoming 'name1' and 'name2' respectively, when they should be A and B. Here is the data table at the moment.

name1 (I want this to be A)name2 (I want this to be B)
1A
2B
3C
4D

Any help is hugely appreciated. I have the same issue with kable tables too.
Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小鸟爱天空丶 2025-02-20 18:44:02

几个选项 -

  1. 使用rename_with -
library(dplyr)

name1 <- 'A'
name2 <- 'B'

datatest %>% rename_with(~c(name1, name2), c(col1, col2))

#If there are only two columns in datatest
datatest %>% rename_with(~c(name1, name2))

#  A B
#1 1 A
#2 2 B
#3 3 C
#4 4 D
  1. 使用命名向量
name <- c(A = 'col1', B = 'col2')
datatest %>% rename(!!name)

Couple of options -

  1. Using rename_with -
library(dplyr)

name1 <- 'A'
name2 <- 'B'

datatest %>% rename_with(~c(name1, name2), c(col1, col2))

#If there are only two columns in datatest
datatest %>% rename_with(~c(name1, name2))

#  A B
#1 1 A
#2 2 B
#3 3 C
#4 4 D
  1. Use a named vector
name <- c(A = 'col1', B = 'col2')
datatest %>% rename(!!name)
っ左 2025-02-20 18:44:02

您可以尝试

datatest %>% rename({{name1}} := col1, {{name2}} := col2)

  A B
1 1 A
2 2 B
3 3 C
4 4 D

You may try

datatest %>% rename({{name1}} := col1, {{name2}} := col2)

  A B
1 1 A
2 2 B
3 3 C
4 4 D
卷耳 2025-02-20 18:44:02

这是使用!setNames的另外一个选项

datatest %>% 
  rename(!!!setNames(names(.), c(name1, name2)))

  A B
1 1 A
2 2 B
3 3 C
4 4 D

Here is one more option using !!!setNames

datatest %>% 
  rename(!!!setNames(names(.), c(name1, name2)))

  A B
1 1 A
2 2 B
3 3 C
4 4 D
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文