using filter in r

In R, the filter() function is used to subset data frames based on specific criteria.

Here is an example of how to use the filter() function to subset rows from a data frame where a particular condition is satisfied:

main.r
# load dplyr package
library(dplyr)

# create sample data frame
df <- data.frame(
  name = c("John", "Jack", "Jill", "Jane"),
  age = c(35, 22, 45, 30),
  gender = c("M", "M", "F", "F")
)

# subset rows where age is greater than 30
df_filtered <- filter(df, age > 30)

# view filtered data frame
df_filtered
308 chars
16 lines

This will result in the following output:

main.r
  name age gender
1 John  35      M
2 Jill  45      F
54 chars
4 lines

In the above example, we loaded the dplyr package, created a sample data frame, and then used the filter() function to subset rows where the age column is greater than 30. The filtered data frame is stored in a new object df_filtered, which we can view to confirm that the rows have been filtered correctly.

related categories

gistlibby LogSnag