[R] Replace / with - in date

David Winsemius dwinsemius at comcast.net
Fri Apr 16 00:07:47 CEST 2010


On Apr 15, 2010, at 5:46 PM, David Winsemius wrote:

> It's going to work better if you offer a non-ambiguous version of  
> your data. Use dump or dput. If you use the dump route, then see the  
> Posting Guide example. If you use dput, then it is as simple as  
> dput(object).
>
> Perhaps (if dfrm is the name of a dataframe):
>
> dput(head(dfrm))
>
>
> On Apr 15, 2010, at 5:27 PM, prem_R wrote:
>
>>
>> This is my sample data
>>
>> 2000/01/01
>
> We cannot tell from the output whether that is a factor or a  
> character vector.
>
>> 2000/01/01
>> 2000/02/01
>> 2000/10/01
>> 2000/19/01
>> 2000/20/01
>> 2000/21/01
>> 2000/22/01
>> 2000/23/01
>> 2000/25/01
>> 2000/26/01
>> 2000/27/01
>> 2000/28/01
>> 2000/29/01
>>
>> Tried using levels function but got the following error .
>> Error in levels(a$date) <- gsub("/", "-", levels(a$date)) :
>> attempt to set an attribute on NULL

So it probably was not a factor variable despite what you offered in  
your previous example. The gsub function should be able to do the  
conversion if it's a character vector, as in this example:

gsub("/","-",
      read.table(textConnection("2000/01/01
  2000/01/01
  2000/02/01
  2000/10/01
  2000/19/01
  2000/20/01
  2000/21/01
  2000/22/01
  2000/23/01
  2000/25/01
  2000/26/01
  2000/27/01
  2000/28/01
  2000/29/01"), header=FALSE, stringsAsFactors=FALSE)[,1] )

--- returns:
  [1] "2000-01-01" "2000-01-01" "2000-02-01" "2000-10-01" "2000-19-01"  
"2000-20-01"
  [7] "2000-21-01" "2000-22-01" "2000-23-01" "2000-25-01" "2000-26-01"  
"2000-27-01"
[13] "2000-28-01" "2000-29-01"

>>
>> Thanks.
>>
>>
>> -- 
>
>
> David Winsemius, MD
> West Hartford, CT
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list