[R] how to read a freetext line ?
Sarah Goslee
sarah.goslee at gmail.com
Thu Nov 17 16:26:22 CET 2011
Hi,
Please copy your replies to r-help so others may participate in the
discussion.
2011/11/17 Jie TANG <totangjie at gmail.com>:
> yes ,I have tried readLines
> by
> config<- readLines(configfile,ok=TRUE,n=-1)
> #but when strsplit is used as below
> food<-unlist(strsplit(config[2].":"))
> #here "food " is a vector
> but the value of food in the text .e.g.12 , is still a string "12
> ",not a integer 12.
> so I have to use strtoi and strtrim ,but I can not decide the value of food
> is 1 digital or more e.g 1 or 12,
> so
> food<-strtoi(strtrim(strsplit(config[2]),":")[2],1))
> ~~~the number
> of the stringtointeger could not be get beforehand in my hand since it
> will be changed by
> other users.so how could I resolve this problem by read the numierical
> number into my configure file ?
> thank you .
>
>
> food<-strtoi(strtrim(strsplit(config[2]),":")[2],1))
>
So your problem is with strsplit(), and not with reading in the data?
I did it in many steps so that you can see how each bit works:
> string1 <- "food:2;1;12" # one of your lines
> string2 <- strsplit(string1, ":") # separate name from values by :
> varname <- string2[[1]][1]
> varname
[1] "food"
> values <- unlist(strsplit(string2[[1]][2], ";")) # separate individual values by ;
> values
[1] "2" "1" "12"
> values <- as.numeric(values) # convert to numbers
> values
[1] 2 1 12
> 2011/11/17 Sarah Goslee <sarah.goslee at gmail.com>
>>
>> Hi,
>>
>> On Thu, Nov 17, 2011 at 9:37 AM, Jie TANG <totangjie at gmail.com> wrote:
>> > hi everyone .
>> > Here I have a text where there are some integer and string
>> > variables.But I
>> > can not read them by readLines and scan
>>
>> I've seen this question several times this morning. If that's you,
>> please do not post multiple times. If you haven't gotten an answer in
>> a couple days, then it's okay to ask again, but the trouble is usually
>> with your question, like here.
>>
>> > the text is :
>> >
>> > weight ;30;130
>> > food:2;1;12
>> > color:white;black
>> >
>> > the first column is the names of the variables and others are the value
>> > of
>> > them.
>> > the column in different line are different.
>> > Can anyone help me ?
>>
>> What have you tried?
>> What format do you need? For instance, reading them in as a single
>> string is easy. Using strsplit() to separate that single string into
>> several strings is easy. But without knowing what you are trying to
>> achieve, there's really no way to help you beyond suggesting those two
>> functions.
>>
More information about the R-help
mailing list