Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using select=-c() in subset function gives error: invalid argument to unary operator

I have a matrix and I would like to eliminate two columns by their names. My code was :

trn_data = subset(trn_data, select = -c("Rye flour","Barley products"))

but R gave me an error message like this:

Error in -c("Rye flour", "Barley products") : 
  invalid argument to unary operator

I tried this

trn_data = subset(trn_data, select = -c(Rye flour,Barley products))

Also returning an error:

Error: unexpected symbol in "trn_data=subset(trn_data,select =-c(Rye flour"

How can I fix this? Is there any other method that can eliminate two columns by their names?

like image 763
Christina Avatar asked Oct 20 '25 04:10

Christina


2 Answers

You should not provide the names as characters to subset. This works:

trn_data_subset <- subset(trn_data, select = -c(`Rye flour`,`Barley products`))

If you have spaces in the name of columns, you should use Grave Accent.

Here's an example using mtcars dataset:

mtexapmple <- mtcars[1:4,]
names(mtexapmple)[1] <- "mpg with space"

mtexapmple
#>                mpg with space cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4                21.0   6  160 110 3.90 2.620 16.46  0  1    4 4
#> Mazda RX4 Wag            21.0   6  160 110 3.90 2.875 17.02  0  1    4 4
#> Datsun 710               22.8   4  108  93 3.85 2.320 18.61  1  1    4 1
#> Hornet 4 Drive           21.4   6  258 110 3.08 3.215 19.44  1  0    3 1


subset(mtexapmple, select = -c(`mpg with space`, cyl))
#>                disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4       160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag   160 110 3.90 2.875 17.02  0  1    4    4
#> Datsun 710      108  93 3.85 2.320 18.61  1  1    4    1
#> Hornet 4 Drive  258 110 3.08 3.215 19.44  1  0    3    1

You can also do it like these:

within(trn_data, rm(`Rye flour`,`Barley products`))

or

trn_data[, !(colnames(trn_data) %in% c("Rye flour","Barley products"))]
like image 68
M-- Avatar answered Oct 21 '25 19:10

M--


With dplyr, we can still use - with double quote

library(dplyr)
mtexample %>%
     select(-"mpg with space")
#               cyl disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4        6  160 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag    6  160 110 3.90 2.875 17.02  0  1    4    4
#Datsun 710       4  108  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive   6  258 110 3.08 3.215 19.44  1  0    3    1

data

mtexample <- mtcars[1:4,]
names(mtexample)[1] <- "mpg with space"
like image 29
akrun Avatar answered Oct 21 '25 19:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!