如果符合条件,则重命名某列中某行的某些值

时间:2018-05-15 16:48:03

标签: dataframe

如果符合特定if语句的某一行,如何重命名某行的某些值?

示例:

    Date    Type   C1 
    2000    none    3
    2000    love    4
    2000    none    6
    2000    none    2
    2000    bad     8

所以我想重命名"爱"并且"坏"在我的专栏中输入" xxx"。

    Date    Type   C1 
    2000    none    3
    2000    xxx     4
    2000    none    6
    2000    none    2
    2000    xxx     8

有一种巧妙的方式吗?

谢谢:)

2 个答案:

答案 0 :(得分:0)

首先,确保它不是一个因素,然后重命名:

df$Type = as.character(df$Type)
df$Type[df$Type %in% c("love", "bad")] = "xxx"

答案 1 :(得分:0)

如果数据是一个因素,您想要重命名因子级别。最简单的方法是使用fct_recode()包中的forcats。如果它是一个字符向量,ifelse如果变化的数量很小则效果很好。如果它很大,case_when包中的dplyr效果很好。

library(forcats)
library(dplyr)

df <- within(df, { # if you use `dplyr`, you can replace this with mutate.  You'd also need to change `<-` to `=` and add `,` at the end of each line.  
  Type_fct1 <- fct_recode(Type, xxx = "love", xxx = "bad")
  # in base R, you need can change the factor labels, but its clunky
  Type_fct2 <- Type
  levels(Type_fct2)[levels(Type_fct2) %in% c("love", "bad")] <- "xxx"

  # methods using character vectors
  Type_chr1 <- ifelse(as.character(Type) %in% c("love", "bad"), "xxx", as.character(Type))
  Type_chr2 <- case_when(
    Type %in% c("love", "bad") ~ "xxx",
    Type == "none" ~ "something_else", # thrown in to show how to use `case_when` with many different criterion.
    TRUE ~ NA_character_
  )

})