create sub dataframe according to columns values in r

In R, you can create a sub dataframe based on the values of specific columns using the subset() function or using dplyr package.

Using subset():

main.r
# create dataframe
df <- data.frame(
  a = c(1, 2, 3),
  b = c("x", "y", "z")
)

# create sub dataframe where column b equals "y"
sub_df <- subset(df, b == "y")
161 chars
9 lines

Using dplyr:

main.r
# load dplyr package
library(dplyr)

# create dataframe
df <- data.frame(
  a = c(1, 2, 3),
  b = c("x", "y", "z")
)

# create sub dataframe where column b equals "y"
sub_df <- df %>% filter(b == "y")
201 chars
12 lines

Both of these methods create a sub dataframe where only the rows that meet the condition specified in the subset() or filter() function are included.

gistlibby LogSnag