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

Categories

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%","40%")
x3 = c(1,2,3)
x = data.frame(x1,x2,x3)
per_col = c(1,2)
x = gsub("%","",x[,per_col])

How can I most efficiently drop the "%" sign in specified columns. Can I apply it to the whole dataframe? This would be useful in the case where I don't know where the percentage columns are.

See Question&Answers more detail:os

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

1 Answer

You can use apply to apply it to the whole data.frame

apply(x, 2, function(y) as.numeric(gsub("%", "", y)))
     x1 x2 x3
[1,] 10 60  1
[2,] 20 50  2
[3,] 30 40  3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...