Replace values in vector where not %in% vector

后端 未结 2 1279
鱼传尺愫
鱼传尺愫 2021-01-26 06:59

Short question:

I can substitute certain variable values like this:

values <- c(\"a\", \"b\", \"a\", \"b\", \"c\", \"a\", \"b\")
df <- data.frame(v         


        
相关标签:
2条回答
  • 2021-01-26 07:29

    What about:

    df[!df[, 1] %in% c("a", "b"), ] <- "x"
    
      values
    1      a
    2      b
    3      a
    4      b
    5      x
    6      a
    7      b
    
    0 讨论(0)
  • 2021-01-26 07:39

    Your example is a bit unclear and not reproducible. However, based on guessing what you actually want, I could suggest trying this option using the data.table package:

    df[values %in% c("a", "b"), values := "x"]
    

    or the dplyr package:

    df %>% mutate(values = ifelse(values %in% c("a","b"), x, values))
    
    0 讨论(0)
提交回复
热议问题