繁体   English   中英

R 中 dataframe 中新变量的重命名和重新编码范围

[英]Rename and recode range of new variables in dataframe in R

我本质上想要重新编码和重命名 dataframe 中的一系列变量。 我正在寻找一种方法来一步完成。

伪代码示例:

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

所需的 output:

     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

如果您想在一个步骤中操作和重命名一系列列,请尝试使用 cross 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

提示:您可以使用seq_along()来创建序列 1, 2, ... 以及所选列,或match()来获取所选列在数据中的位置,即
.names = "x{match(.col, names(df))}"

下面的代码允许您将列号输入到 for 循环中,不确定这是否是您想要的。

require(dplyr)

df <- iris %>% head()


for(i in 1:3){
  names(df)[i] <- paste0("x",i)
}

df

输出:

   x1  x2  x3 Petal.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

您可以通过这种方式将连续数字添加到具有相同前缀的n列:

df <- iris %>% head()

n <- 3
colnames(df)[1:n] <- sprintf("x%s",1:n)

output:

# x1  x2  x3 Petal.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

在任何不连续的列数中:

n <- c(1,3,5)
colnames(df)[n] <- sprintf("x%s",n)

#   x1 Sepal.Width  x3  Petal.Width     x5
# 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

暂无
暂无

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

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