1

I want to delete 2 columns named-ItemID_na and Item.Type1_na. I have below code to delete.

test_input<-subset(test_input,select = -c(ItemId_na, Item.Type1_na))  

i am getting below error-

Error: unexpected string constant in "test_input<-subset(test_input,select = -c(ItemId_na, Item.Type1_na))

Can you please help as I am new to R.

akrun
  • 874,273
  • 37
  • 540
  • 662
Arpit Sisodia
  • 570
  • 5
  • 18
  • Have you tried my solution? – akrun Mar 20 '16 at 06:14
  • Your code looks fine. My guess is that you have a typo somewhere. Hint: Add spaces in your code. It makes it easier to read and spot errors. Other hint, try to generate a reproducible example and share that rather than just the error message. In creating the reproducible example, you might stumble upon the answer on your own. – A5C1D2H2I1M1N2O1R2T1 Mar 21 '16 at 05:27

2 Answers2

3

Try subsetting your data frame to retain only the columns you want:

drops <- c('ItemId_na', 'Item.Type1_na')
test_input <- test_input[ , !(names(test_input) %in% drops)]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

There are two problems in the OP's code. One is that the column names that we need to delete is not quoted. Second, the select argument doesn't take - argument. So we can use setdiff to get the column names that are not "ItemId_na" or "Item.Type1_na".

subset(test_input,select = setdiff(names(test_input),
            c("ItemId_na", "Item.Type1_na")))

The select option from dplyr takes the - option

library(dplyr)
test_input %>%
       select(-ItemId_na, -Item.Type1_na)

data

test_input <- structure(list(ID = c(1L, 1L, 1L, 1L, 2L, 
2L), Category = c("X", 
"X", "X", "X", "X", "X"), ItemId_na = c(2L, 2L, 2L, 2L,
3L, 3L
), Item.Type1_na = c(1L, 2L, 3L, 4L, 1L, 2L)), 
.Names = c("ID", 
"Category", "ItemId_na", "Item.Type1_na"),
row.names = c(NA, 6L), class = "data.frame")
akrun
  • 874,273
  • 37
  • 540
  • 662