2021年1月29日星期五

Multiplying all the values from a dataframe by a single column from another dataframe and save the results in a new object

I am trying to create a time-series in R from the population reduction of tree species from 2000–2019. To do this, I'm using two data frames: 1) species relative density per site and 2) numbers of trees per site (same sites as before), something like:

#creating a table of years x site, where the values are the number of trees per site  year1 = c(1122, 1134, 1114, 1715)  year2 = c(1115, 11165, 1170, 1117)  year3 = c(1162, 1110, 1111, 1130)  year_site <- data.frame(year1, year2, year3)      #creating a table of species x site (the same number and order of sites as before),  #where the values are relative density per site  sp1 = c(0.50, 0.1, 0.01)  sp2 = c(0.25, 0.15, 0.10)  sp3 = c(0.005, 0.005, 0.045)  sp4 = c(0.060, 0.00035, 0.01)  sp5 = c(0.5, 0.4, 0.4)  sp_site <- data.frame(sp1, sp2, sp3, sp4, sp5)  

So, I want to

  1. multiply the sp_site dataframe by each vector of year_site,
  2. sum each sp_site$sp[i] and then
  3. save the summed values of each species for each year in a new object

I'm trying to use for loops but I'm unable to proceed. It was something like:

#creating a list() to save the results  sp_list <- setNames(vector('list', length(sp_site)), sp_site)    for (y in names(year_site)){    for (sp in names(sp_site)){      out <- sum(year_site[,y]*sp_list[, sp])      sp_list[[sp]] <- out     }  }  

The code above only loops one year for each species, but I need all the years saved, continually.

Can you guys help me?

https://stackoverflow.com/questions/65963990/multiplying-all-the-values-from-a-dataframe-by-a-single-column-from-another-data January 30, 2021 at 10:14AM

没有评论:

发表评论