Creating a table of species traits weighted by abundance in R -


i've table of species traits (>400 species, scores each of 50 traits). wish weight abundance of species recorded @ number of sites (150 sites), creating table of summed scores of each individual trait in each site. can manually (see below), not sure how code more efficiently.

t1 <- c(0,1,0); t2 <- c(0,0,0.5); t3 <- c(1,0,0.5); t4 <- c(1,0,0.5); t5 <- c(0,1,0.5); df.trt <- data.frame(t1,t2,t3,t4,t5) rownames(df.trt) <- c("species.a", "species.b", "species.c") rm(t1,t2,t3,t4,t5)  site.1 <- c(10,0,1); site.2 <- c(0,3,7); site.3 <- c(2,4,100) df.abund <- data.frame(site.1,site.2,site.3) rownames(df.abund) <- c("species.a", "species.b", "species.c") rm(site.1,site.2,site.3) ### table of species traits df.trt  ### table of species abundance df.abund  ###generating weighted table manually site.1 <- c(sum(df.trt[,1]*df.abund[,1]),             sum(df.trt[,2]*df.abund[,1]), sum(df.trt[,3]*df.abund[,1]),             sum(df.trt[,4]*df.abund[,1]), sum(df.trt[,5]*df.abund[,1])) site.2 <- c(sum(df.trt[,1]*df.abund[,2]),             sum(df.trt[,2]*df.abund[,2]), sum(df.trt[,3]*df.abund[,2]),             sum(df.trt[,4]*df.abund[,2]), sum(df.trt[,5]*df.abund[,2])) site.3 <- c(sum(df.trt[,1]*df.abund[,3]),             sum(df.trt[,2]*df.abund[,3]), sum(df.trt[,3]*df.abund[,3]),             sum(df.trt[,4]*df.abund[,3]), sum(df.trt[,5]*df.abund[,3])) wt.trt <- data.frame(site.1, site.2, site.3) rm(site.1,site.2,site.3) rownames(wt.trt) <- c("t1","t2","t3","t4","t5") wt.trt <- t(wt.trt); wt.trt <- data.frame(wt.trt)  ###to generate following table wt.trt 

i understand shouldn't onerous task, i'm having trouble figuring out how go it. advice can provide.

ps: i'm new r , first post on stack overflow, apologies if i'm accidentally not adhering site rules/etiquette. don't think duplicate query (or @ least, i'm unable find has helped)

the code have above turned loop. here ways of hiding/avoiding loop:

do.call(rbind,   lapply(df.abund, function(x) colsums(x*df.trt)) ) #        t1   t2   t3   t4   t5 # site.1  0  0.5 10.5 10.5  0.5 # site.2  3  3.5  3.5  3.5  6.5 # site.3  4 50.0 52.0 52.0 54.0 

this computes each row , binds them together. (try running second line see.)

sapply(df.abund, function(x) colsums(x*df.trt)) #    site.1 site.2 site.3 # t1    0.0    3.0      4 # t2    0.5    3.5     50 # t3   10.5    3.5     52 # t4   10.5    3.5     52 # t5    0.5    6.5     54 

this computes whole thing in 1 go, unfortunately flips rows , columns around.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -