[R] summary tables with tapply
Uwe Ligges
ligges at statistik.uni-dortmund.de
Sat Mar 11 15:22:54 CET 2006
Stefanie von Felten, IPW&IfU wrote:
> Hello everyone,
>
> #I have a long table with a factor Plotfac:
> > Plotfac[1:20]
> [1] 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5
> 5 6 6
>
> #there is the species diversity of each plot (Plotfac):
> DataSort$div[1:20]
> [1] 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 2 2 2 2
>
> #and the plant community growing in each plot:
> > DataSort$community[1:20]
> [1] DLRT_1 DLRT_1 DLRT_1 DLRT_1 DLRT_1 DLRT_1 DLRT_1 DLRT_1
> DLRT_1 DLRT_1 DLRT_1 DLRT_1 DLRT_1 DLRT_1 DLRT_1 DLRT_1 ARR HOL
> [18] ARR HOL ARR HOL ARR HOL
>
> #Now I want to have a summary table with data on the plotlevel
> #I define the new plot variable:
> Newplot<-levels(Plotfac)#a vector with all plotnumbers 1-n)
> >Newplot[1:10]
> [1] "1" "2" "3" "4" "5" "6" "7" "8" "15" "16"
>
> #the new div variable (div is numeric, so mean is no problem)
> PlotDiv<-tapply(DataSort$div,Plotfac,mean)
> > PlotDiv[1:10]
> 1 2 3 4 5 6 7 8 15 16
> 4 4 4 4 2 2 2 2 2 2
>
> #BUT HOW CAN I DO THIS WITH THE CHARACTER COMMUNITY?
> #A rather unsatisfactory solution:
> community<-tapply(DataSort$community,Plotfac,as.character)
> results in:
> community[1:5]
> $"1"
> [1] "DLRT_1" "DLRT_1" "DLRT_1" "DLRT_1"
>
> $"2"
> [1] "DLRT_1" "DLRT_1" "DLRT_1" "DLRT_1"
>
> $"3"
> [1] "DLRT_1" "DLRT_1" "DLRT_1" "DLRT_1"
>
> $"4"
> [1] "DLRT_1" "DLRT_1" "DLRT_1" "DLRT_1"
>
> $"5"
> [1] "ARR HOL" "ARR HOL"
> #how can I make community look like
> "DLRT_1", DLRT_1","DLRT_1","DLRT_1","ARR HOL"...
> #without repeating the community of each observation within a plot? Is
> it possible to extract a single "value" out of these repeated structures?
I guess you want
sapply(community, "[", 1)
Uwe Ligges
> Thanks for any suggestions!
>
> Steffi
>
>
More information about the R-help
mailing list