r - Subsetting every x amount of columns as separate sites -
i need function recognises every x amount of columns separate site. in df1 below there 8 columns, 4 sites each consisting of 2 variables. previously, have used procedure answered here selecting column sequences , creating variables.
set.seed(24) df1 <- as.data.frame(matrix(sample(0:20, 8*10, replace=true), ncol=8))
i need calculate column sum total each variable obtained.
colsums <- as.data.frame(t(colsums(df1)))
i subsequently split dataframe using technique...
lst1 <- setnames(lapply(split(1:ncol(colsums), as.numeric(gl(ncol(colsums), 2, ncol(colsums)))), function(i) colsums[,i]), paste0('site', 1:4)) list2env(lst1, envir=.globalenv)
and organise 1 dataframe...
combined <- as.matrix(mapply(c,site1,site2,site3,site4)) rownames(combined) <- c("site.1","site.2","site.3","site.4")
whilst technique has been great on smaller dataframes, there substantial amount of sites (>500) typing out each site following mapply function takes lot of code , lead sites getting missed off if i'm typing them in manually. there easy way overcome following colsums stage?
a matrix vector dimensions. matrices stored in column-major order in r.
the call matrix(colsums, nrow=2)
should lot.
nb.: polluting "global" environment bad idea.
Comments
Post a Comment