0

I am trying to subtract the mean (using the sweep function) from each column of the inbuilt longley data set in R, except from the ‘Year’ column. I have tried

sweep(apply(longley,2,mean),2,-c["Year"])

but is giving me the error

Error in c["Year"] : object of type 'builtin' is not subsettable

It seems like a simple question but I just can't figure out how to exclude the 'Year' column in this function

Thank you

Rory78
  • 15
  • 1
  • 4
  • You could do this without `sweep` – akrun Oct 23 '14 at 12:18
  • I understand but I am in the process of learning R and I am playing around with the sweep function at the moment – Rory78 Oct 23 '14 at 12:23
  • possible duplicate of [How to drop columns by name in a data frame](http://stackoverflow.com/questions/5234117/how-to-drop-columns-by-name-in-a-data-frame) – Henrik Oct 23 '14 at 12:24

1 Answers1

0

You could do this using:

  nm1 <- setdiff(colnames(longley), "Year")
  res1 <- longley[nm1]-colMeans(longley[nm1])[col(longley[nm1])]

Or using sweep

 res2 <- sweep(longley[nm1], 2, FUN=`-`, apply(longley[nm1], 2, mean))
 identical(res1, res2)
 #[1] TRUE

Or you can replace the apply with colMeans

 sweep(longley[nm1], 2, FUN=`-`, colMeans(longley[nm1]))
akrun
  • 874,273
  • 37
  • 540
  • 662