Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset Data Based On Elements In List

In R, I am trying to subset the data.frame named Data by using element stored in a list.

Data

Data <- read.table(text = "  Data_x  Data_y  Column_X 
                                -34      12       A
                                -36      20       D
                                -36      12       E
                                -34      18       F
                                -34      10       B
                                -35      24       A
                                -35      16       B
                                -33      22       B
                                -33      14       C
                                -35      22       D", header = T)

Code

variableData <- list("A", "B")
subsetData_1 <- subset(Data, Column_X == variableData[1])
subsetData_2 <- subset(Data, Column_X == variableData[2])
subsetData <- rbind(subsetData_1, subsetData_2)

Problems

  • First, the elements in the list can be more than two and is not fixed. Can even have more than 100 elements.
  • Second, I want to keep only one data.frame which will store all the subset data extracted using all the elements in list. If there are more elements, lets say 100, then I don't want to repeat subset() for each of the elements.

Is there a better way to approach this than the code above? As my approach is not good enough and will take performance hit.

Any suggestion will be helpful, thanks.

like image 642
Chetan Arvind Patil Avatar asked Jan 29 '23 21:01

Chetan Arvind Patil


1 Answers

%in% should do the trick:

subset(Data, Column_X %in% variableData)

You can also use dplyr and filter:

Data %>% filter(Column_X %in% variableData)
like image 131
Alper t. Turker Avatar answered Feb 02 '23 09:02

Alper t. Turker