Hi peoples, I'm trying to work out a function which will allow me to relace column names on the basis of substrings within the existing names. e.g. I'd like: blah.Na blah2.Na blah3.Mg blah4.Mg blah5.K blah6.K R1 x x x x x x R2 x x x x x x ... to become: Na (%) Na (%) Mg (%) Mg (%) K (ppm) K (ppm) R1 x x x x x x R2 x x x x x x ... So based on whether the existing column name has a .Na or a .K etc. in it somewhere, I'd like it to be replaced with a name which I can provide i.e. Na (%) or K (%). So far I can't even figure out how to replace a column name:>aa[colnames(aa)=="blah3.Mg"]_colnames("Mg (%)")Error in matrix(value, n, p) : No data to replace in matrix(...) help please Cheers Jeremy
"Jeremy Z Butler" <jerrytheshrub at hotmail.com> writes:> So far I can't even figure out how to replace a column name: > > >aa[colnames(aa)=="blah3.Mg"]_colnames("Mg (%)") > Error in matrix(value, n, p) : No data to replace in matrix(...)You replace the column names by replacing elements of the second component of the dimnames. The easiest way to do this is to extract the column names as a vector of character strings then replace components of this vector then install it as the second component of the dimnames. cnams = dimnames(aa)[[2]] cnams[which(cnams == 'blah3.Mg')] = 'Mg (%)' ... dimnames(aa)[[2]] = cnams BTW, the use of '_' as the assignment operator is deprecated. It will be disabled in future versions of R. We prefer '=' or '<-' as the use of '_' results in code that is difficult to read. -- Douglas Bates bates at stat.wisc.edu Statistics Department 608/262-2598 University of Wisconsin - Madison http://www.stat.wisc.edu/~bates/