2

I am trying to write a function in R to subset data based on ID in a data frame like below, but the function I wrote does not work and it doesn't give me an error message either. Can someone let me know how to fix my function code?

subset1<-function(id){df2<-df[df$ID==id,]}

enter image description here

2
  • 1
    Do you need to write your own function? Else, if you want to filter rows, use dplyr::filter(df, ID == id), or use dplyr::select to select columns, Commented May 18, 2016 at 13:16
  • Thanks Daniel! Very informative!! Commented May 18, 2016 at 13:22

1 Answer 1

3

We can use [[ inside a function

f1 <- function(id){
      df[df[["ID"]] == id,]
    }
f1(11)
#  ID Item
#1 11    a
Sign up to request clarification or add additional context in comments.

1 Comment

Ohh! Thanks for such a quick response..! This works perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.