[英]Create new column from conditions on multiple columns in R
我正在尝试编写的内容将使用 Python 中的 apply 函数编写:
def categorise(row):
if row['colC'] > 0 and row['colC'] <= 99:
return 'A'
elif row['colC'] > 100 and row['colC'] <= 199:
return 'B'
elif row['colC'] > 200 and row['colC'] <= 299:
return 'C'
return 'D'
df['colF'] = df.apply(lambda row: categorise(row), axis=1)
这是我目前拥有的 R 代码
myf <- function(x) {
count <- 0
if(x[,"BMICat"]==4){
count = count +1}
if(x[,"SleepTimeCat"]==1 | x[,"SleepTimeCat"]==4){
count= count+1}
if(x[,"MentalHealthCat"]==3){
count= count+1}
if(x[,"Smoking"]==TRUE){
count= count+1}
if(x[,"PhysicalActivity"]==FALSE){
count= count+1}
return(count)
}
dfAugment %>%
mutate(BadHabits= myf(.))
我经常被困在尝试在 R 中应用这种模式,我的方法在 R 中不常见吗?
如果我正确理解您的问题,一个可能的解决方案是创建虚拟变量,然后将它们加在一起。
library(dplyr)
dfAugment <- data.frame(BMICat = c(1, 2, 4, 4),
SleepTimeCat = c(1, 2, 3, 4))
dfAugment |>
mutate(risk_sum = if_else(BMICat == 4, 1, 0) +
if_else(SleepTimeCat == 1 | SleepTimeCat == 4, 1, 0))
输出
#> BMICat SleepTimeCat risk_sum
#> 1 1 1 1
#> 2 2 2 0
#> 3 4 3 1
#> 4 4 4 2
由reprex 包于 2022-06-22 创建 (v2.0.1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.