[R] convert into numeric variable

Gabor Grothendieck ggrothendieck at gmail.com
Wed Oct 22 03:10:51 CEST 2008


Use readLines to read your data into Lines.in.  Then
delete percentages and right parens followed by replacing
left parens followed by zero or more spaces with a minus.
Then re-read using read.table.

Lines <- "4.61%    ( 4.11%) 29.85%   ( 1.27%) 16.04%   21.31%   14.09% 39.71%
4.61%    ( 4.11%) 29.85%   ( 1.27%) 16.04%   21.31%   14.09% 39.71%"

# Lines.in <- readLines("myfile.dat")
Lines.in <- readLines(textConnection(Lines))

Lines.in <- gsub("[%)]", "", Lines.in)
Lines.in <- gsub("[(] *", "-", Lines.in)
DF <- read.table(textConnection(Lines.in))


On Tue, Oct 21, 2008 at 8:02 PM, Young Cho <young.stat at gmail.com> wrote:
> Hi,
>
> I have an accounting data with "%" at the end and "()" for negative.
> E.g.  if I read in with read.table, then R reads in as a factor:
>
> [11625] 4.61%    ( 4.11%) 29.85%   ( 1.27%) 16.04%   21.31%   14.09%
> 39.71%
> [11633] 3.03%    17.39%   80.13%
> 6648 Levels:  ( 0.00%) ( 0.03%) ( 0.04%) ( 0.05%) ( 0.06%) ( 0.07%) ...
> 99.70%
> And I was wondering how to convert this column into numeric numbers in R?
>
> Thanks a lot!
>
> Young
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list