0

I am trying to rename the rows of a data frame with the following syntax: the letter C combined with the column number. However, I need the number to have 4 digits since that will make sorting it later on easier. There are 5631 rows, so for example, I would want C0001 to be the first row, C0124 to be the 124th row, C2493 to be the 2493rd row, and so on.

I figured I could do it in a series of loops as such, and it works fine for the first 10 rows:

for(i in 1:9){
  rownames(data)[i] = paste("C", 0, 0, 0, i, sep = "")
}

However, when I try to do it for rows 10-99, I get the following error:

for(i in 10:99){
  rownames(data)[i] = paste("C", 0, 0, i, sep = "")
}

Error in `.rowNamesDF<-`(x, value = value) : invalid 'row.names' length

This is what happened:

rownames(data)[1:99]
 [1] "G0001" "G0002" "G0003" "G0004" "G0005" "G0006" "G0007" "G0008" "G0009"
[10] "G0010" "G0011" "G0012" "G0013" "G0014" "G0015" "G0016" "G0017" "G0018"
[19] "G0019" "G0020" "G0021" "G0022" "G0023" "G0024" "G0025" "G0026" "G0027"
[28] "G0028" "G0029" "G0030" "G0031" "G0032" "G0033" "G0034" "G0035" "G0036"
[37] "G0037" "G0038" "G0039" "G0040" "G0041" "G0042" "G0043" "G0044" "G0045"
[46] "G0046" "G0047" "G0048" "G0049" "G0050" "G0051" "G0052" "G0053" "G0054"
[55] "G0055" "G0056" "G0057" "G0058" "G0059" "G0060" "G0061" "G0062" NA     
[64] NA      NA      NA      NA      NA      NA      NA      NA      NA     
[73] NA      NA      NA      NA      NA      NA      NA      NA      NA     
[82] NA      NA      NA      NA      NA      NA      NA      NA      NA     
[91] NA      NA      NA      NA      NA      NA      NA      NA      NA 

Why does this loop only work up to 62, and then stop?

I would also be welcome to any suggestions on how to do this in a more efficient way!

akenny430
  • 305
  • 3
  • 16
  • 3
    Try this: `sprintf("%04d",1:100)`. – joran Jun 28 '19 at 14:52
  • 2
    You don't even need a loop if you just do `rownames(data) <- sprintf("G%04d", 1:nrow(data))` – MrFlick Jun 28 '19 at 14:52
  • (Side note: I've seen some Windows systems where for some reason the internal sprintf system call doesn't support that feature, for some reason.) – joran Jun 28 '19 at 14:54
  • @joran (That's odd. I'm on a windows machine now and it worked. I can't think of any previous cases where I've noticed a difference between OS with this function and I switch around a lot) – MrFlick Jun 28 '19 at 14:55
  • Thank you guys, worked perfectly and is obviously a lot cleaner than a bunch of for-loops. My apologies for the repeat question! – akenny430 Jun 28 '19 at 14:57
  • 1
    @MrFlick It was an old Windows version, 7 I think, and I'm pretty sure it was specific to the `0` option, and kind of hinted at in the docs with "For numbers, pad to the field width with leading zeros. For characters, this zero-pads on some platforms and is ignored on others." So it must have only not worked with character inputs or something. – joran Jun 28 '19 at 15:08

0 Answers0