Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

r - I want to replace each value in vector x with "Yes" if corresponding value from vector y isn't "No"

Using this code in R:

x <- c("No", "Yes", "No")
y <- c("Yes", "No", "No")
df <- data.frame(x, y)

my.yes <- function(x,y) {
  for (i in length(x)){
  x[i] <<- ifelse(x[i]=="No" && y[i]!="No", "Yes", "No")
  }
}

my.yes(df$x, df$y)

I want x in df to be as such: "Yes", "Yes", "No"

Thanks in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An other bae solution:

deni = function(df){
  df$x[df$y != "No"] <- "Yes"
  return(df$x)
}

Using @ruibarradas benchmark:

Unit: microseconds
   expr      min        lq      mean    median       uq      max neval
   deni  115.201  159.2500  248.8230  208.8015  241.002 3819.700   100
    rui  278.701  344.1005  507.1501  443.7010  485.601 6291.501   100
 akrun1  383.700  511.6010  665.6150  611.8505  699.901 4568.001   100
 akrun2 2990.601 3465.2015 3913.3211 3698.8510 4181.801 8792.201   100

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...