Question

Suppose this is the data:

2011/03/06,17:24:17.100,EUR/USD,1.40200,3000000

I want to extract the last digit of the price, even if it is zero. Here is the code:

library(data.table)
library(stringr)
types<-list(date="TEXT",time="TEXT",curr="TEXT",price="TEXT",volume="INTEGER")
mydata=read.table("data.out", sep="," , header=FALSE)
setnames(mydata, names(types))
str_sub(mydata$price,start=-1)

this is the result: "2", it ignores zeros. I read the price as a text so I should get "0".

EDIT, Thanks to jlhoward:

mydata<-read.table(...) is converting the price and volume columns to numeric automatically. I used mydata<- read.table(...,colClasses="character"), problem solved.

Was it helpful?

Solution

You aren't stating where your data come from. If you use read.csv on a file, you'll have the items separated into columns immediately. You can even get them from the keyboard, e.g.:

read.csv(stdin(),header=FALSE)
0: 300,hello,40.2
1: 
#   V1    V2   V3
# 1 300 hello 40.2

Then you could do foo<- dat$V3%%10 , as in my comment above, to get the last digit.

OTHER TIPS

Here is the method I talked about in the comment.

   line = "2011/03/06,17:24:17.100,EUR/USD,1.40200,3000000"
    sp = line.split(",")
    sp
    ['2011/03/06', '17:24:17.100', 'EUR/USD', '1.40200', '3000000']
    price = sp[-2]
    price
    '1.40200'
    last = price[-1]
    last
    '0'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top