r - Use value in new variable name -


i trying build loop step through each site, site calculate frequencies of response, , put results in new data frame. after loop want able combine of site data frames like:

site     genus     freq 1                50 1        b         30 1        c         20 2                70 2        b         10 2        c         20 

but need names (of vectors, dataframes) change each time through loop. think can using sitenum variable, how insert new variable names? way tried (below) treats part of string, doesn't insert value name.

i feel want use placeholder %, don't know how variable names.

> sitenum <- 1 > (site in coralsites){     > csub_sitenum <- subset(dfrmc, site==coralsites[sitenum])      > cgrfreq_sitenum <- numeric(length(coralgenera))     > (genus in coralgenera){         > cgrfreq_sitenum[genusnum] <- mean(dfrmc$genus == coralgenera[genusnum])*100         > genusnum <- genusnum + 1         > }     > names(cgrfreq_sitenum) <- c(coralgenera)     > site_sitenum <- c(site)     > cg_sitenum <- data.frame(coralgenera,cgrfreq_sitenum,site_sitenum)     > sitenum <- sitenum + 1     > } 

your question stated asks how can create bunch of variables, e.g. cgrfreq_1, cgrfreq_2, ..., name of variable indicates site number corresponds (1, 2, ...). while can such thing functions assign, not practice few reasons:

  1. it makes code generate variables more complicated because littered calls assign , get , paste0.
  2. it makes data more difficult manipulate afterwards -- you'll need (either manually or programmatically) identify variables of type, grab values get or mget, , them.

instead, you'll find easier work other r functions perform aggregation you. in case you're looking generate each site/genus pairing percentage of data points @ site particular genus value. can done in few lines of code aggregate function:

# sample data: (dat <- data.frame(site=c(rep(1, 5), rep(2, 5)), genus=c(rep("a", 3), rep("b", 6), "a"))) #    site genus # 1     1     # 2     1     # 3     1     # 4     1     b # 5     1     b # 6     2     b # 7     2     b # 8     2     b # 9     2     b # 10    2      # calculate frequencies dat$freq <- 1 res <- aggregate(freq~genus+site, data=dat, sum) res$freq <- 100 * res$freq / table(dat$site)[as.character(res$site)] res #   genus site freq # 1        1   60 # 2     b    1   40 # 3        2   20 # 4     b    2   80 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -