Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am new to R and Rstudio. I am working on a handwriting digits project. For my frontend, I am using R shiny. I got the dataset from Kaggle. This is the function which helps to render the average representation of digits 

# Produce a plot containing the average representations of digits

  output$digitAvgRep <- renderImage({

    ## For visualising traing data

    dataFrame<-as.matrix(data())

    ##Color ramp def.

    colors<-c('white','red')

    cus_col<-colorRampPalette(colors=colors)

    ## Plot the average image of each digit

    par(mfrow=c(4,3),pty='s',mar=c(1,1,1,1),xaxt='n',yaxt='n')

    all_img<-array(dim=c(10,28*28))

    for(di in 0:9)

    {

      print(di)

      all_img[di+1,]<-apply(dataFrame[dataFrame[,1]==di,-1],2,sum)

      all_img[di+1,]<-all_img[di+1,]/max(all_img[di+1,])*255

      z<-array(all_img[di+1,],dim=c(28,28))

      z<-z[,28:1] ##right side up1

      image(1:28,1:28,z,main=di,col=cus_col(256))

    }

  })

Then pass the varibale to UI.R using the below code:

# User renderUI to dynamically create objects in the ui.R 

  output$tb <- renderUI({

    if(is.null(data()))

      h5("No data loaded.")

    else

      tabsetPanel(

        tabPanel("About file", tableOutput("filedf")),

        tabPanel("RawData", tableOutput("table")),

        tabPanel("Summary", tableOutput("sum")),

        tabPanel("Digit Distribution",plotOutput("digitDist")),

        tabPanel("Average Digit Representation", imageOutput("digitAvgRep")))

  })

When I run the application I am getting the output as follows:

[1] 0

Error in all_img[di + 1, ] <- apply(dataFrame[dataFrame[, 1] == di, -1],  : 

  number of items to replace is not a multiple of replacement length

Can anyone help me solve this?

1 Answer

0 votes
by (36.8k points)

The error which you are getting tells that you are trying to insert a new vector of length which is shorter than the column. use the following code as an example:

## create a matrix that is 6 rows and 2 columns

mat <- matrix(1:12, 6,2) 

## try to replace first column with a vector of length 3

## works fine because 6 is a multiple of 3

mat[,1] <- 1:3 

## try to replace first column with a vector of length 5

## Fails because 6 is not a multiple of 5, try the same exception.

mat[,1] <- 1:5 

##   number of items to replace is not a multiple of replacement length

Hence you need to reconsider your application statement. Try storing the results in the list than in the matrix.

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

Browse Categories

...