Open3

Rで列名を変える方法いろいろ

yuuyuu

Rで存在する列名だけを変更する方法

library(dplyr)
map_rename_col <- c(
  MPG_NEW = "mpg",
  CYL_NEW = "cyl",
  no_name = "no_col"
)

mtcars %>%
  select(1:5) %>% 
  rename(any_of(map_rename_col))

#>                     MPG_NEW CYL_NEW  disp  hp drat
#> Mazda RX4              21.0       6 160.0 110 3.90
#> Mazda RX4 Wag          21.0       6 160.0 110 3.90
#> Datsun 710             22.8       4 108.0  93 3.85
#> Hornet 4 Drive         21.4       6 258.0 110 3.08  
yuuyuu

すべての列名に名前を追加する方法は下記の通り

baseRを使う方法

iris_new <- iris
colnames(iris_new) <- paste0("foo_", colnames(iris_new))  # Add prefix

tidyverseを使う方法

 add_prefix <- function(.x, .prefix) {
   return(str_c(.prefix, "_", .x))
 }
 
 iris %>% 
    rename_with(~add_prefix(., "add_pre"), everything())
yuuyuu

sapply()を使って列名にprefixを追加する方法

iris_new <- iris
colnames(iris_new) <- sapply(colnames(iris_new), function(x) paste0("prefix_", x))
head(iris_new)
#>   prefix_Sepal.Length prefix_Sepal.Width prefix_Petal.Length prefix_Petal.Width prefix_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

参考) https://www.r-bloggers.com/2024/10/how-to-add-prefix-to-column-names-in-base-r-a-comprehensive-guide-for-beginners/