[R] assign index to colnames(matrix)

Jim Lemon jim at bitwrit.com.au
Sat Feb 23 02:22:12 CET 2013


On 02/23/2013 11:34 AM, Prew, Paul wrote:
> Hello,  I’m trying to follow the syntax of a script from a journal website.  In order to create a regression formula used later in the script, the regression matrix must have column names “X1”, “X2”, etc.  I have tried to assign these column names to my matrix ScoutRSM.mat using a for loop, but I don’t know how to interpret the error message.  Suggestions?  Thanks, Paul
>
>
> ====================================================
> ====== instructions about dimnames(X)[[2]] = "X1","X2",...  =======
> ====================================================
>
> function(binstr)
> {
>    # makes formula for regression
>    # must make sure dimnames(X)[[2]] = "X1","X2",...
>    ind<-which(binstr==1)
>    rht<- paste("X", ind, sep="", collapse="+")
>    ans<-paste("y ~ ", rht)
>    return(as.formula(ans))
> }
>
>
> #######################################
> ##############  my for loop  ##############
> #######################################
>
> for (i in 1:dim(ScoutRSM.mat)[2]  {
> colnames(ScoutRSM.mat)[i]<- paste("X", i, sep = “”))
> }
>
>> for(i in 1:dim(ScoutRSM.mat)[2]) {
> +   colnames(ScoutRSM.mat)[i]<- paste("X",i, sep = "")
> + }
> Error in `colnames<-`(`*tmp*`, value = "X1") :
>    length of 'dimnames' [2] not equal to array extent
>
Hi Paul,
You don't really need the loop, try:

colnames(ScoutRSM.mat)<-paste("X",1:dim(ScoutRSM.mat)[2],sep="")

Jim



More information about the R-help mailing list