Filtering on basis of row data

Hi all,

I have a data frame like this-

Category Sub category Option
A A_1 Q1
A A_2 Q2
A A_3 Q3
B B_1 Q4
B B_2 Q5
C C_1 Q6
C C_2 Q7
D D_3 Q8
D D_4 Q9

I want the output as such the data gets filtered based on Category basis . Like when I select "A", the output should be-
A_1
A_2,
A_3.

and subsequently for all Category.

I tried using-

fct<- function(quest)
        {
          quest<-c(1:nrow(df))
          for(i in 1:nrow(df))
          {
            if(df$Category[i]==df$Category[i+1])
            {
              quest[i]<- print(paste(df$`Sub-Category`[i]))
            }
          }
          return(quest)
        }
        
        opt<- fct(quest)

How to get this?

Kindly check the question again.

As @Yarnabrina noted

If your data frame is named DF,

dput(DF)

will output the data frame shown below. Better yet do a full reprex.

The reprex below is not as convenient as dplyr::filter but will do the job

my_filter <- function(x,y,z) x[which(x[,y] == z),]

DF <- structure(list(Category = c(
  "A", "A", "A", "B", "B", "C", "C",
  "D", "D"
), Sub_category = c(
  "A_1", "A_2", "A_3", "B_1", "B_2",
  "C_1", "C_2", "D_3", "D_4"
), Option = c(
  "Q1", "Q2", "Q3", "Q4",
  "Q5", "Q6", "Q7", "Q8", "Q9"
)), class = c(
  "spec_tbl_df", "tbl_df",
  "tbl", "data.frame"
), row.names = c(NA, -9L), spec = structure(list(
  cols = list(Category = structure(list(), class = c(
    "collector_character",
    "collector"
  )), Sub_category = structure(list(), class = c(
    "collector_character",
    "collector"
  )), Option = structure(list(), class = c(
    "collector_character",
    "collector"
  ))), default = structure(list(), class = c(
    "collector_guess",
    "collector"
  )), skip = 1L
), class = "col_spec"))


my_filter(DF,"Category","A")
#> # A tibble: 3 x 3
#>   Category Sub_category Option
#>   <chr>    <chr>        <chr> 
#> 1 A        A_1          Q1    
#> 2 A        A_2          Q2    
#> 3 A        A_3          Q3

Created on 2021-01-11 by the reprex package (v0.3.0.9001)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.