• R语言
  • R语言 怎么根据两列映射关系,替换数据框中的字符?

如何让数据框z中的1、2、3、4分别精确匹配、替换为A、B、C、D,
而不影响里面的其它数字内容?

z <- data.frame(colnames=c("1","2","3","4"),
                "1"=c("1","9.98","9.99","3.33"),
                "2"=c("4.44","2",'4.44',"4.44"),
                "3"=c("9.99","2.22","3","9.99"),
                "4"=c("4.43","2.23","2.21","4"),
           check.names = F)
mgsub(z, c("1","2","3","4"),c("A","B","C","D"))

case_when构建一个替换的函数,

My_Change <- function(invec){
    case_when(
        invec == "1" ~ "A", 
        invec == "2" ~ "B", 
        invec == "3" ~ "C", 
        invec == "4" ~ "D", 
        TRUE ~ as.character(invec)
    )
}

然后就可以mutate

z %>%
    mutate(across(
        .cols = everything(), 
        .fns = My_Change))

或者直接 sapply

as.data.frame(sapply(z, My_Change))

    monster_white

    那要么这样?

    My_Change2 <- function(invec){
        idx <- which(invec %in% as.character(1 : 4))
        invec[idx] <- LETTERS[as.integer(invec[idx])]
        return(invec)
    }

    利用A,B,C,D恰好是字母中排序1,2,3,4的关系。

      fenguoerbian
      字符形式的一一映射,也可以用 named vector 来构建

      my_change <- function(input, change_logic) {
        
        output <- change_logic[match(input, names(change_logic))]
        
        names(output) <- NULL
        
        return(output)
        
      }
      
      my_change(
        c('2', '1', '2', '4', '3'),
        change_logic = c('1' = 'A', '2' = 'B', '3' = 'C', '4' = 'D')
        # change_logic = c('A', 'B', 'C', 'D') |> setNames(1:4)
      )