# [R] Converting text to numbers

Dan Chan dchan at GFC.STATE.GA.US
Wed Sep 27 22:47:34 CEST 2006

```Hi,

I have Forecast Class and Observed Class in a data matrix as below.

> Sample1
FCT OBS
1   1  5
2   2   4
3  3-  3+
4   3   3
5  3+  3-
6   4   2
7   5   1

I want to find the difference between Observed and Forecast Classes.
How can I get this done?

I tried to following to convert the 1 through 5 classes, to 1 through 7
for both OBS and FCT column.
> Sample1\$OBS2 <- Sample1\$OBS
> levels(Sample1\$OBS2) <- sub('5',7,levels(Sample1\$OBS2),fixed=TRUE)
> levels(Sample1\$OBS2) <- sub('4',6,levels(Sample1\$OBS2),fixed=TRUE)
> levels(Sample1\$OBS2) <- sub('3+',5,levels(Sample1\$OBS2), fixed=TRUE)
> levels(Sample1\$OBS2) <- sub('3',4,levels(Sample1\$OBS2),fixed=TRUE)
> levels(Sample1\$OBS2) <- sub('4-',3,levels(Sample1\$OBS2),fixed=TRUE)
> Sample1
FCT OBS FCT2 OBS2
1   1  5     1   7
2   2   4    2    6
3  3-  3+    3    5
4   3   3    4    4
5  3+  3-    5    3
6   4   2    6    2
7   5   1    7    1

All looks good, but as I do the following, I encounter an error.
> Sample1\$OBS2- Sample1\$FCT2
[1] NA NA NA NA NA NA NA
Warning message:
- not meaningful for factors in: Ops.factor(Sample1\$OBS2, Sample1\$FCT2)

Then, I tried to convert them to numbers using the following.
> Sample1\$FCT2 <- as.numeric(Sample1\$FCT2)
> Sample1\$OBS2 <- as.numeric(Sample1\$OBS2)
> Sample1
FCT OBS FCT2 OBS2
1   1  5     1    7
2   2   4    2    6
3  3-  3+    4    5
4   3   3    3    3
5  3+  3-    5    4
6   4   2    6    2
7   5   1    7    1

Sample1\$FCT2[3] and Sample1\$FCT2[4] switched values.

I think it has something to do with the following:
> Sample1\$OBS
[1] 5  4  3+ 3  3- 2   1
Levels:  1 2 3 3- 3+ 4 5

But, I don't know why and how to fix it.

Any ideas?

Thank you.

Daniel Chan
Meteorologist
Georgia Forestry Commission
P O Box 819
Macon, GA
31202
Tel: 478-751-3508
Fax: 478-751-3465

```