简体   繁体   English

如何根据特定行的条件更改 R 个单元格(数据框)的值>?

[英]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 上仅针对特定索引应用以下条件。

  • C1 should be equal to 0 C1 应等于 0
  • A random number should be less than 0.5随机数应小于 0.5

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:我的问题是:

  • In my function, How do I apply the conditions to a certain column only ie C1 (I have tried using DF[rowsIndex,c(1)], but gives an error在我的 function 中,如何将条件仅应用于特定列,即 C1(我尝试使用 DF[rowsIndex,c(1)],但给出错误
  • Is there any other approach I can take Since this approach is not giving me any results and the same DF is printed.有没有我可以采用的其他方法因为这种方法没有给我任何结果并且打印了相同的 DF。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM