[R] creating a factor
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Tue Feb 3 13:39:04 CET 2004
Simon Hosking <simon.hosking at general.monash.edu.au> writes:
> Hi list,
> I'd like to make a factor with seven 1s and three 2s using the
> factor() function.
> That is,
>
> 1
> 1
> 1
> 1
> 1
> 1
> 1
> 2
> 2
> 2
>
>
> I will then bind this factor to the matrix below using cbind.data.frame().
>
> 0.56 0.48
> 0.22 0.59
> 0.32 0.64
> 0.26 0.60
> 0.25 0.38
> 0.24 0.45
> 0.56 0.67
> 0.78 0.97
> 0.87 0.79
> 0.82 0.85
>
>
>
> I am new to R and have been using various manuals and have made many attempts without success
> any help appreciated.
> thanks,
> Simon
> f <- factor(scan())
1: 1
2: 1
3: 1
4: 1
5: 1
6: 1
7: 1
8: 2
9: 2
10: 2
11:
Read 10 items
> df <- read.table(stdin())
0: 0.56 0.48
1: 0.22 0.59
2: 0.32 0.64
3: 0.26 0.60
4: 0.25 0.38
6: 0.24 0.45
7: 0.56 0.67
8: 0.78 0.97
9: 0.87 0.79
10: 0.82 0.85
11:
> cbind(df,f)
V1 V2 f
1 0.56 0.48 1
2 0.22 0.59 1
3 0.32 0.64 1
4 0.26 0.60 1
5 0.25 0.38 1
6 0.24 0.45 1
7 0.56 0.67 1
8 0.78 0.97 2
9 0.87 0.79 2
10 0.82 0.85 2
> summary(cbind(df,f))
V1 V2 f
Min. :0.2200 Min. :0.3800 1:7
1st Qu.:0.2525 1st Qu.:0.5075 2:3
Median :0.4400 Median :0.6200
Mean :0.4880 Mean :0.6420
3rd Qu.:0.7250 3rd Qu.:0.7600
Max. :0.8700 Max. :0.9700
so what was the problem??
I suspect your df was a matrix, not a data frame: just take
as.data.frame first. Otherwise, you'll find that f gets converted to
numeric.
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list