Alexander
Alexander

Reputation: 4645

Change column names of selected columns

I would like to change column names with the first row of the data.

This solution in my previous post works for that part.

OTH, inside of the setNames function I would like to add one more level to change the column names only for selected columns.

Here is the problem

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,]))

which gives

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

ok fair enough! but I want to keep col names lets say X1,X2, and X3 and change only from X4 to max number of columns

So I try

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

Error in [.data.frame(., 1, X4:max(ncol(.))) : object 'X4' not found

Ok maybe I need to specify column location by number

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

As we can see here there is a shift in the names. Naming started from the first column even I specified the column location with 4:max(ncol(.))

Why this is happening ? Any help would be appreciated!

The expected output. (I also would like to remove the first row after this setName operation)

  X1 X2 X3 13  8
1 78 27 81 75 61

Upvotes: 0

Views: 1125

Answers (1)

DJV
DJV

Reputation: 4873

This would do the trick:

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

Upvotes: 1

Related Questions