Extract Data with Conditions in R

In R language, you can use the subset function to extract data based on conditions. Here is an example:

Suppose there is a dataframe df with two columns “age” and “gender”, and we want to extract all data where age is greater than 20 years old.

subset(df, age > 20)

This will return a new data frame that includes all data with age greater than 20 years old.

Additionally, data can be extracted based on conditions using conditional statements like ifelse. For example, if we want to label data with ages greater than 20 as “Adult” and ages less than or equal to 20 as “Youth”:

df$age_group <- ifelse(df$age > 20, "Adult", "Youth")

This will create a new column “age_group” in the dataframe df and assign values based on the result of a condition.

bannerAds