Suppose I have the following DF:
C1 | C2 |
---|---|
0 | 0 |
1 | 1 |
1 | 1 |
0 | 0 |
. | . |
. | . |
I now want to apply these following conditions on the Dataframe:
- C1的值应为1
- 0到5之间的随机整数应小于2
如果这两个条件都为真,我将该行的C1和C2值更改为2
我知道这可以通过使用apply函数来实现,我使用了以下方法:
C1 <- c(0, 1,1,0,1,0,1,0,1,0,1)
C2 <- c(0, 1,1,0,1,0,1,0,1,0,1)
df <- data.frame(C1, C2)
fun <- function(x){
if (sample(0:5, 1) < 2){
x[1:2] <- 2
}
return (x)
}
index <- df$C1 ==1 // First Condition
processed_Df <-t(apply(df[index,],1,fun)) // Applies Second Condition
df[index,] <- processed_Df
Output:
C1 | C2 |
---|---|
0 | 0 |
2 | 2 |
1 | 1 |
0 | 0 |
. | . |
. | . |
有些行同时满足这两个条件,有些行则不满足(这是主要条件)
现在我想用矢量化实现同样的效果,而不使用循环或apply
函数.我唯一的困惑是"如果我不使用apply
,那么根据条件的结果,每一行不是都会得到相同的结果吗?(例如,下面:)
df$C1 <- ifelse(df$C1==1 & sample(0:5, 1) < 5, 2, df$C1)
这会将我的DF中C1==2的所有行更改为2,而此时可能会有许多1.
有没有一种方法可以在不使用apply
函数的情况下为每行的第二个条件获得不同的结果?希望我的问题有道理.
谢谢