[英]How to change values of R cells (dataframe) based on a condition for specific rows>?
I have the following dataframe,我有以下 dataframe,
C1 C1 | C2 C2 | C3 C3 |
---|---|---|
0 0 | 0 0 | 0 0 |
1 1个 | 1 1个 | 0 0 |
0 0 | 0 0 | 0 0 |
1 1个 | 1 1个 | 0 0 |
0 0 | 0 0 | 0 0 |
I want to now apply the following condition on the dataframe for specific indexes only.我现在想在 dataframe 上仅针对特定索引应用以下条件。
If the above conditions match, I want to change the value of the Cell in C1 and C2 to 1 else do nothing.如果满足以上条件,我想将C1和C2中Cell的值改为1,否则什么都不做。
I am trying the following: (rowIndex is the specific indexes on which I want to apply the conditions)我正在尝试以下操作:(rowIndex 是我要应用条件的特定索引)
apply(DF[rowsIndex,], 2, fun)
where fun is:有趣的地方是:
fun<- function(x) {
ifelse(x==0,ifelse(runif(n=1)<0.5,x <- 1,x),x )
print(x)
}
My questions are:我的问题是:
Thanks谢谢
If you want to stay in base R:如果你想留在基地 R:
#your dataframe
DF <- data.frame(C1 = c(0, 1, 0, 1, 0),
C2 = c(0, 1, 0, 1, 0),
C3 = c(0, 0, 0, 0, 0))
fun<- function(x) {
if(x[1]==0 & runif(n=1)<0.5) {
x[1:2] <- 1
}
return(x)
}
#your selection of rows you want to process
rowsIndex <- c(1, 2, 3, 4)
#Using MARGIN = 1 applies the function to the rows of a dataframe
#this returns a dataframe containing your selected and processed rows
DF_processed <- t(apply(DF[rowsIndex,], 1, fun))
#replace the selected rows in the original DF by the processed rows
DF[rowsIndex, ] <- DF_processed
print(DF)
Something like this?是这样的吗?
library(dplyr)
df %>%
mutate(across(c(C1, C2), ~ifelse(C1 == 0 & runif(1) < 0.5, 1, .)))
C1 C2 C3
1 1 0 0
2 1 1 0
3 1 0 0
4 1 1 0
5 1 0 0
Applying it to your function:将其应用于您的 function:
fun<- function(df, x, y) {
df %>%
mutate(across(c({{x}}, {{y}}), ~ifelse({{x}} == 0 & runif(1) < 0.5, 1, .)))
}
fun(df, C1, C2)
C1 C2 C3
1 0 0 0
2 1 1 0
3 0 0 0
4 1 1 0
5 0 0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.