Kaja
Kaja

Reputation: 3057

converting char to integer in a vector

I am reading data from an excel file. Data in the excel file is like this:

45,25,12,36,14

with this code:

wb <- loadWorkbook("C:\\users\\bla\\bla\\Muster.xls")
dat <-readWorksheet(wb, sheet=getSheets(wb)[1], startRow=2, endRow=35, startCol=1, endCol=1,header=FALSE)
datalist<-dat[,1]
datalist

I have this output

[1]   "45,25,12,36,14"
[2]   "33,52,26,37,40"
...

I would like to do mathematic operation with these outputs like this:

k<-datalist[1]-datalist[2]

but I get an error, becuase they are in char format. my question is now:

How can I convert these char to a real integer in a vector? and then do mathematic operation on them

Upvotes: 0

Views: 100

Answers (2)

SlowLearner
SlowLearner

Reputation: 7997

As an addendum, if each column contains a single figure then you can use the ColTypes argument to readWorksheet of the XLConnect library (which is what you are using in the above snippet) to ensure that the data you read is interpreted appropriately. If you had one column with a date followed by four holding numerics, you would do something like this, for example:

my.cols <- c("Date",
          rep("numeric",4))

wb = loadWorkbook(my.file)
tn <- readWorksheet(wb, my.sheet, colTypes = my.cols)

Upvotes: 1

Mark Heckmann
Mark Heckmann

Reputation: 11431

You could split the string into separate numbers (strsplit) and convert them into numerics which will (as.numeric). x is datalist in your case.

x <- c("45,25,12,36,14", "33,52,26,37,40")
l <- strsplit(x, ",")
d <- sapply(l, as.numeric)
d

      [,1] [,2]
[1,]   45   33
[2,]   25   52
[3,]   12   26
[4,]   36   37
[5,]   14   40

Now you have a matrix containing the values in each column. The rest is straightforward,

d[, 1] - d[, 2]

[1]  12 -27 -14  -1 -26

Upvotes: 3

Related Questions