我基本上想要重新编码和重命名数据帧中的一系列变量.我正在寻找一种方法,一步到位.

伪代码中的示例:

require(dplyr)

df <- iris %>% head()

df %>% mutate(
   paste0("x", 1:3) = across(       # In the example I want to rename 
      Sepal.Length:Petal.Length,    # the variables I've selected
      ~ .x + 1                      # and recoded to "x1" ... "x5"
   )
)
df

期望输出:

     x1    x2    x3 Petal.Width Species
  <dbl> <dbl> <dbl>       <dbl>   <fct>
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_with()是你想要的.之后,可以使用mutate(across(...))操作这些重命名的列.

library(dplyr)

df %>%
  rename_with(~ paste0("x", seq_along(.x)), Sepal.Length:Petal.Length) %>%
  mutate(across(x1:x3, ~ .x * 10))

  x1 x2 x3 Petal.Width Species
1 51 35 14         0.2  setosa
2 49 30 14         0.2  setosa
3 47 32 13         0.2  setosa
4 46 31 15         0.2  setosa
5 50 36 14         0.2  setosa
6 54 39 17         0.4  setosa

如果要在一个步骤中操作和重命名一系列列,请try across()中的参数.names.

df %>%
  mutate(across(Sepal.Length:Petal.Length, ~ .x * 10,
                .names = "x{seq_along(.col)}"),
         .keep = "unused", .after = 1)

  x1 x2 x3 Petal.Width Species
1 51 35 14         0.2  setosa
2 49 30 14         0.2  setosa
3 47 32 13         0.2  setosa
4 46 31 15         0.2  setosa
5 50 36 14         0.2  setosa
6 54 39 17         0.4  setosa

Hint: You can use seq_along() to create a sequence 1, 2, ... along with the selected columns, or match() to get the positions of the selected columns in the data, i.e.
.names = "x{match(.col, names(df))}".

R相关问答推荐

单击 map 后,将坐标复制到剪贴板

在R底座中更改白天和夜晚的背景 colored颜色

MCMC和零事件二元逻辑回归

在"gt"表中添加第二个"groupname_col",而不连接列值

如何直接从Fortran到R的数组大小?

二维样条,严格以一个参数递增

即使硬币没有被抛出,也要保持对其的跟踪

将多列合并为单独的名称—值对

如何通过匹配R中所有可能的组合来从宽到长旋转多个列?

安全地测试文件是否通过R打开

在不对R中的变量分组的情况下取两行的平均值

如何修改GT表中组名行的 colored颜色 ?

使用dqur在不同变量上创建具有多个条件的变量

通过匹配另一个表(查找表)中的列值来填充数据表,并在另一个变量上进行内插

在R中使用ggraph包排列和着色圆

真实世界坐标的逆st_变换

如何修复geom_rect中的层错误?

如何从矩阵绘制环弦图

向数据添加标签

等价于Plot_ly R中的geom_函数