0

I need to rename columns with names “V4, V5, etc... V503” to be time series in increments of two ms (i.e. “-100-98, 97-95, etc... zip to 900 ms”).

These are 2 second increments for columns that contain brain data from -100 ms to 900ms. I’ve tried using names() and substring() but R didn’t like the numeric aspect. Can anyone help? Thank you!

  • Can you share the code you've tried? Sounds like you're on the track with zip to 900. There are some useful answers here regarding enumeration in R https://stackoverflow.com/questions/9281323/zip-or-enumerate-in-r – Lex Jun 01 '20 at 23:30
  • You can also convert integers to string with `as.String(x)` – Lex Jun 01 '20 at 23:31
  • Can you make your post clear regarding what you have and what you want? How does the series `-100-98`, `97-95` reach 900? – Ronak Shah Jun 01 '20 at 23:58

1 Answers1

1

You need to turn the numbers into a string using as.character. You can just paste offsetting sequences together for their ranges and it will coerce the data to a string using the - separator. Then you need to remove instances of -- with gsub so that negative values don't have double -. Note that you need to use back ticks when subsetting these columns.

sq <- seq(-100, 898, by=2)
sq2 <- seq(-98, 900, by=2)

nams <- paste(sq, sq2, sep='-')
nams <- gsub('--', '-', nams)

# generating fake dataframe
n <- length(sq)
df <- matrix(data=rep(1, n), nrow = 1, ncol=n)
df <- as.data.frame(df)

# replace names

colnames(df) <- nams

head(df)
at80
  • 710
  • 4
  • 8
  • I was stuck on this too and glad to see your elegant solution @at80. I would advise OP to avoid using '-' as the delimiter though, and using `nams <- paste(sq, sq2, sep=':')` in your third line. Having a hypen separate negative numbers is confusing to the eye. – Jope Jun 02 '20 at 01:09