How to implement multiple condition matching data in R language?

In R language, you can use logical operators and conditional statements to achieve multiple condition matching of data.

Assuming there is a data frame named df with two columns, age and gender, we are looking to identify data where age is over 30 and gender is “male”.

You can use the logical operator “&” to achieve matching with multiple conditions.

# 创建示例数据框
df <- data.frame(age = c(25, 35, 40, 28, 45),
                 gender = c("male", "female", "male", "female", "male"))

# 多条件匹配
matched_data <- df[df$age > 30 & df$gender == "male", ]

In the above code, df$age > 30 filters data where age is greater than 30, while df$gender == “male” filters data where gender is “male”. The two conditions are connected with the logical operator “&”.

Finally, assign the condition matching result to the matched_data variable to obtain the data that meets the criteria.

To achieve multi-condition matching for an “or” condition, you can use the logical operator “|”.

# 或条件匹配
matched_data <- df[df$age > 30 | df$gender == "male", ]

In the code above, df$age > 30 selects data where the age is greater than 30, and df$gender == “male” selects data where the gender is “male”. The two conditions are connected using the logical operator “|”.

Finally, assigning the matched results to matched_data will give us the data that meets the criteria.

bannerAds