Modify R Data Frames with Conditions

In R language, you can use conditional statements and logical operators to modify data based on conditions. Here is a simple example:

Assume there is a data frame, df, containing a column named “age,” and we want to change the age of people who are 18 years old or older to “adult.”

# 创建一个示例数据框df
df <- data.frame(name = c("Alice", "Bob", "Cathy", "David"),
                 age = c(20, 15, 25, 12))

# 使用条件语句和逻辑运算符修改数据
df$age[df$age >= 18] <- "成年"

# 打印修改后的数据框
print(df)

After running the above code, the ages of people above 18 years old in the data frame df will be changed to “adult”.

bannerAds