Removing Percentages from a Data Frame

后端 未结 1 601
滥情空心
滥情空心 2021-01-19 07:26

I have a dataframe that originated from an excel file. It has the usual headers above the columns but some of the columns have % signs in them which I want to remove.

1条回答
  •  悲&欢浪女
    2021-01-19 08:07

    Based on @Arun's comment and imaging how your data.frame looks like:

    > DF <- data.frame(X = paste0(1:5,'%'), 
                       Y = paste0(2*(1:5),'%'),
                       Z = 3*(1:5), stringsAsFactors=FALSE )
    
    > DF # this is how I imagine your data.frame looks like
       X   Y  Z
    1 1%  2%  3
    2 2%  4%  6
    3 3%  6%  9
    4 4%  8% 12
    5 5% 10% 15
    
    > # Using @Arun's suggestion
    > (DF2 <- data.frame(sapply(DF, function(x) as.numeric(gsub("%", "", x)))))
      X  Y  Z
    1 1  2  3
    2 2  4  6
    3 3  6  9
    4 4  8 12
    5 5 10 15
    

    I added as.numeric in sapply call for the resulting cols to be numeric, if I don't use as.numeric the result will be factor. Check it out using sapply(DF2, class)

    0 讨论(0)
提交回复
热议问题