【问题标题】:Change column names of selected columns更改选定列的列名
【发布时间】:2018-05-30 20:45:50
【问题描述】:

我想用数据的第一行更改列名。

This solution 在我之前的帖子中适用于该部分。

OTH,在 setNames 函数内部,我想再添加一层以仅更改选定列的列名。

问题来了

df <- data.frame(replicate(10,sample(100,2,rep=TRUE)))

  X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1 76 44 89 13  8 31 12 21 50  36
2 78 27 81 75 61 84  2 65 43  51

library(dplyr)
df1 <- df %>%
  select(X1:X5)%>%
  setNames(as.character(.[1,]))

给了

> print(df1)
  76 44 89 13  8
1 76 44 89 13  8
2 78 27 81 75 61

好公平!但我想保留 col 名称让我们说 X1,X2X3 并且仅从 X4 更改为最大列数

所以我试试

df1 <- df %>%
  select(X1:X5)%>%
  setNames(as.character(.[1,X4:max(ncol(.))]))

[.data.frame(., 1, X4:max(ncol(.))) 中的错误:找不到对象“X4”

好的,也许我需要按数字指定列位置

df1 <- df %>%
  select(X1:X5)%>%
  setNames(as.character(.[1,4:max(ncol(.))]))

> print(df1)
  13  8 NA NA NA
1 76 44 89 13  8
2 78 27 81 75 61

正如我们在这里看到的,名称发生了变化。即使我用4:max(ncol(.)) 指定了列位置,也从第一列开始命名

为什么会这样? 任何帮助将不胜感激!

预期的输出。 (我也想删除这个 setName 操作后的第一行)

  X1 X2 X3 13  8
1 78 27 81 75 61

【问题讨论】:

    标签: r dplyr rename


    【解决方案1】:

    这样就可以了:

    require(tidyverse)
    
    #Using your dataset
    df <- data.frame(replicate(10,sample(100,2,rep=TRUE)))
    
    df %>% 
      set_names(c(names(df)[1:3], as.character(.[1,])[4:10])) %>% 
      rownames_to_column("index") %>% 
      filter(index != 1 ) %>% 
      select(-index)
    
      X1 X2 X3 16 56 51 11 21 61 37
    1 43 15 75 38 70 20 63 70 53 79
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-04
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 2011-07-28
      相关资源
      最近更新 更多