[R] Split a dataframe by rownames and/or colnames
Tim Richter-Heitmann
trichter at uni-bremen.de
Fri Feb 20 18:33:30 CET 2015
Dear List,
Consider this example
df <- data.frame(matrix(rnorm(9*9), ncol=9))
names(df) <- c("c_1", "d_1", "e_1", "a_p", "b_p", "c_p", "1_o1", "2_o1",
"3_o1")
row.names(df) <- names(df)
indx <- gsub(".*_", "", names(df))
I can split the dataframe by the index that is given in the column.names
after the underscore "_".
list2env(
setNames(
lapply(split(colnames(df), indx), function(x) df[x]),
paste('df', sort(unique(indx)), sep="_")),
envir=.GlobalEnv)
However, i changed my mind and want to do it now by rownames. Exchanging
colnames with rownames does not work, it gives the exact same output (9
rows x 3 columns). I could do
as.data.frame(t(df_x),
but maybe that is not elegant.
What would be the solution for splitting the dataframe by rows?
Thank you very much!
--
Tim Richter-Heitmann
More information about the R-help
mailing list