【问题标题】:How to rename all column names in tibble by passing a character vector?如何通过传递字符向量重命名 tibble 中的所有列名?
【发布时间】:2020-05-27 18:32:18
【问题描述】:

我有一个名为 X 的多列(超过 500 列),以“X”+整数的格式命名。小标题看起来像这样。

# A tibble: 7,352 x 561
      X1       X2     X3     X4     X5     X6        
    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  
 1 0.289 -0.0203  -0.133 -0.995 -0.983 -0.914 
 2 0.278 -0.0164  -0.124 -0.998 -0.975 -0.960 

txt 文件不包含列名,但它们位于另一个 txt 文件中,我已将其读入另一个 tibble。这个 tibble 大小为 561x1。

我想做的是使用行值重命名 tibble x 的所有列名(=将 tibble 转换为名为 y 的字符向量)。

我试过 dplyr 函数 rename_all 没有结果。

这是一个我认为非常接近实际工作的示例,但我不太了解如何使用函数 list

> rename_all(x,list(paste0(y)))

RStudio 命令行中的上述命令产生以下错误消息:

Error in get(.x, .env, mode = "function") : 
  object 'tBodyAcc-mean()-X' of mode 'function' was not found

tBodyAcc-mean()-X是字符向量y第一行的值。

我尝试在谷歌上搜索错误消息,但到目前为止我不知道是什么原因造成的,以及我应该如何修改 rename_all 命令以使其正常工作。

非常感谢任何帮助!

【问题讨论】:

  • 为什么不只是names(df) &lt;- y?

标签: r dplyr tibble


【解决方案1】:

你可以使用:

library(dplyr)

x %>% rename_all(~y %>% pull(col))
#     a       b      c      d      e      f
#1 0.289 -0.0203 -0.133 -0.995 -0.983 -0.914
#2 0.278 -0.0164 -0.124 -0.998 -0.975 -0.960

或者简单地在基础 R 中:

names(x) <- y$col

其中col 是y 数据框中的列名。

数据

x <- structure(list(X1 = c(0.289, 0.278), X2 = c(-0.0203, -0.0164), 
X3 = c(-0.133, -0.124), X4 = c(-0.995, -0.998), X5 = c(-0.983, 
-0.975), X6 = c(-0.914, -0.96)), class = "data.frame", row.names = c("1", "2"))
y <- tibble(col = letters[1:6])

【讨论】:

    【解决方案2】:

    在正确建议的基本 R 解决方案的基础上,我编写了一个与管道兼容的小型函数来完成这项工作:

    set_names <- function(x, colnames) {
      # Do some checks
      if (! "data.frame" %in% class(x)) stop("Argument must be a data.frame")
      if (class(colnames) != "character") stop("New names must be character")
      if (length(names(x)) != length(colnames)) stop("Invalid nr. of new names")
       # Actual replacement of  column names     
      names(x) <- colnames
      return(x)
    }
    

    示例用法:

    X <- read_xslx(fname,sname) %>%     # Read the data
      select(1:2) %>%                   # Use only first 2 columns
      set_names(c("name","value")) %>%  # set proper name
      filter(value>5)                   # select data of interest
    

    【讨论】:

      【解决方案3】:

      使用rename_at,你可以编写如下代码:

      x1 <- x %>% 
              rename_at(., names(x), funs(c(letters[1:6])))
      

      【讨论】:

        猜你喜欢
        • 2022-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-11
        • 2021-05-21
        • 2017-11-11
        • 2021-09-07
        • 1970-01-01
        相关资源
        最近更新 更多