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
list
can be more than two and is not fixed. Can even have more than 100 elements.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.
%in%
should do the trick:
subset(Data, Column_X %in% variableData)
You can also use dplyr
and filter:
Data %>% filter(Column_X %in% variableData)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With