且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据其他列中的值有条件地更改数据框列

更新时间:2022-12-09 15:40:52

使用 sapply 内部内的内容无法正常工作。 内部中的函数仅使用 sapply 的返回值。但是在您的代码中, sapply 返回 NULL 。因此,之内不会修改数据框。

The use of sapply inside within does not work as you expect. The function within does only use the returned value of sapply. But in your code, sapply returns NULL. Hence, within does not modify the data frame.

这里是一种更简单的修改数据框而无需循环或 apply

Here is an easier way to modify the data frame without a loop or sapply:

idx <- df$outcome == "1"
df1 <- within(df, {age[idx] <- age[idx] + 15; 
                   sex[idx] <- sample(c("m", "f"), sum(idx), 
                                      replace = TRUE, prob = c(0.8, 0.2))})

现在,数据帧不同:

> tapply(df$age, df$outcome, mean)
       0        1 
60.46341 57.55556 
> tapply(df1$age, df$outcome, mean)
       0        1 
60.46341 72.55556 

> tapply(df$sex, df$outcome, summary)
$`0`
 f  m 
24 17 

$`1`
f m 
2 7 

> tapply(df1$sex, df$outcome, summary)
$`0`
 f  m 
24 17 

$`1`
f m 
1 8