sapply - trying to drop few columns from dataset

Currently i working on a dataset in Rstudio and trying to drop few columns to perform a task.

For example, the following code excludes columns 6, 7, and 8 from the mean calculation.

sapply(cereals.df[,-c[6:8]], mean, na.rm=TRUE)

but when i run the code i set below error message, Can someone please help?

sapply(cereals[,-c[6:8]], mean, na.rm=TRUE)

Error: unexpected ')' in "sapply(cereals[,-c[6:8], mean, na.rm=TRUE)"

Dataset details :

'data.frame': 77 obs. of 16 variables:
$ name : Factor w/ 77 levels "100%_Bran","100%_Natural_Bran",..: 1 2 3 4 5 6 7 8 9 10 ...
$ mfr : Factor w/ 7 levels "A","G","K","N",..: 4 6 3 3 7 2 3 2 7 5 ...
$ type : Factor w/ 2 levels "C","H": 1 1 1 1 1 1 1 1 1 1 ...
$ calories: int 70 120 70 50 110 110 110 130 90 90 ...
$ protein : int 4 3 4 4 2 2 2 3 2 3 ...
$ fat : int 1 5 1 0 2 2 0 2 1 0 ...
$ sodium : int 130 15 260 140 200 180 125 210 200 210 ...
$ fiber : num 10 2 9 14 1 1.5 1 2 4 5 ...
$ carbo : num 5 8 7 8 14 10.5 11 18 15 13 ...
$ sugars : int 6 8 5 0 8 10 14 8 6 5 ...
$ potass : int 280 135 320 330 NA 70 30 100 125 190 ...
$ vitamins: int 25 0 25 25 25 25 25 25 25 25 ...
$ shelf : int 3 3 3 3 3 1 2 3 1 3 ...
$ weight : num 1 1 1 1 1 1 1 1.33 1 1 ...
$ cups : num 0.33 1 0.33 0.5 0.75 0.75 1 0.75 0.67 0.67 ...
$ rating : num 68.4 34 59.4 93.7 34.4 ...

There are some problems with your syntax. Try this (I'm assuming your data frame is named cereals).

sapply(cereals[, -c(6:8)], mean, na.rm = TRUE)

Thanks, for the responses your solution, It worked!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.