Applying gsub to various columns

后端 未结 6 1822
无人及你
无人及你 2020-12-10 04:13

What is the most efficient way to apply gsub to various columns? The following does not work

x1=c(\"10%\",\"20%\",\"30%\")
x2=c(\"60%\",\"50%\",         


        
6条回答
  •  悲哀的现实
    2020-12-10 04:43

    To add on docendo discimus' answer, an extension with non-adjacent columns and returning a data.frame:

    x1 <- c("10%", "20%", "30%")
    x2 <- c("60%", "50%", "40%")
    x3 <- c(1, 2, 3)
    x4 <- c("60%", "50%", "40%")
    
    x <- data.frame(x1, x2, x3, x4)
    
    x[, c(1:2, 4)] <- as.data.frame(apply(x[,c(1:2, 4)], 2,
                                             function(x) {
                                               as.numeric(gsub("%", "", x))}
    ))
    
    > x
      x1 x2 x3 x4
    1 10 60  1 60
    2 20 50  2 50
    3 30 40  3 40
    
    > class(x)
    [1] "data.frame"
    

提交回复
热议问题