0

So I have created a data.frame that has n columns like so:

df <- as.data.frame(matrix(nrow = 3, ncol = 15))

It looks like this:

  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15
1 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA
2 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA
3 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA

I want change every Nth column name, so it looks like this:

  A  V2 V3 B  V5 V6 C  V8 V9  D  V11 V12  E  V14 V15
1 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA
2 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA
3 NA NA NA NA NA NA NA NA NA  NA  NA  NA  NA  NA  NA

I have made this sequence, that gives me colnames I want:

colnames(df[,seq(1,ncol(df),3)])

The output:

[1] "V1"  "V4"  "V7"  "V10" "V13"

But when I try to change names nothing happens:

colnames(df[,seq(1,ncol(df),3)]) <- c("A","B","C","D","E")

I also tried this, but it only changes the first column and it gives warning message:

names <- colnames(df[,seq(1,ncol(df),3)])
colnames(df)[colnames(df) == names] <- c("A","B","C","D","E")

The warning message:

Warning message:
In colnames(df)[colnames(df) == names] <- c("A", "B", "C", "D",  :
  number of items to replace is not a multiple of replacement length

Thank you in advance for your help, I appreciate every answer :)

aynber
  • 22,380
  • 8
  • 50
  • 63
QuMiVe
  • 137
  • 9

2 Answers2

2

You can modify certain column names based on the position, but you need to put the [] brackets outside the colnames function:

df <- as.data.frame(matrix(nrow = 3, ncol = 15))
colnames(df)[seq(1,ncol(df),3)] <- c("A","B","C","D","E")
df
#>    A V2 V3  B V5 V6  C V8 V9  D V11 V12  E V14 V15
#> 1 NA NA NA NA NA NA NA NA NA NA  NA  NA NA  NA  NA
#> 2 NA NA NA NA NA NA NA NA NA NA  NA  NA NA  NA  NA
#> 3 NA NA NA NA NA NA NA NA NA NA  NA  NA NA  NA  NA
PLY
  • 531
  • 2
  • 4
  • 18
  • well...what to say...I also tried it, but it did not work...then I reset my Rstudio and it works... :D :D thank you very much. In 10 min I will accept your answer. – QuMiVe Nov 23 '20 at 14:52
  • you can also use `%%` here if you want too: `colnames(df)[seq(colnames(df)) %%3 == 1] <- c("A","B","C","D","E")` – Mike Nov 23 '20 at 15:05
0

You can also try this code. The value k allows modifying the spacing in names:

#Data
df <- as.data.frame(matrix(nrow = 3, ncol = 15))
#Seq for names
k <- 3
v1 <- seq(1,length(names(df)),by=k)
vchar <- LETTERS[1:length(v1)]
#Replace
names(df)[v1] <- vchar

Output:

   A V2 V3  B V5 V6  C V8 V9  D V11 V12  E V14 V15
1 NA NA NA NA NA NA NA NA NA NA  NA  NA NA  NA  NA
2 NA NA NA NA NA NA NA NA NA NA  NA  NA NA  NA  NA
3 NA NA NA NA NA NA NA NA NA NA  NA  NA NA  NA  NA
Duck
  • 39,058
  • 13
  • 42
  • 84