Home > Software engineering >  Skip the variable if that is not present in the matrix
Skip the variable if that is not present in the matrix

Time:09-24

I have a list like this

list<-c("mpg","hp","wt","aa")

And a matrix as like this

  data<-as.matrix(mtcars)

If I try to subset the matrix as this

 data[,list]

It will show an error like this "Error in data[, list] : subscript out of bounds".because of the list variable aa .

My question is how to skip the variable if that is not present in the matrix and print the rest ? Is there any function for this ? (For my case it is not possible to edit the list).

CodePudding user response:

You can use the %in% and colnames() function to compare the values of the column names that are in the list.

list<-c("mpg","hp","wt","aa")

data<-as.matrix(mtcars)

data[,colnames(data) %in% list]

The top of the output is:

head(data[,colnames(data) %in% list])
                   mpg  hp    wt
Mazda RX4         21.0 110 2.620
Mazda RX4 Wag     21.0 110 2.875
Datsun 710        22.8  93 2.320
Hornet 4 Drive    21.4 110 3.215
Hornet Sportabout 18.7 175 3.440
Valiant           18.1 105 3.460

CodePudding user response:

You may also use intersect

data[,intersect(list, colnames(data))]

#                     mpg  hp    wt
#Mazda RX4           21.0 110 2.620
#Mazda RX4 Wag       21.0 110 2.875
#Datsun 710          22.8  93 2.320
#Hornet 4 Drive      21.4 110 3.215
#Hornet Sportabout   18.7 175 3.440
#Valiant             18.1 105 3.460
  •  Tags:  
  • r
  • Related