R Error: incorrect number of dimensions (2 Examples)

 

This tutorial explains how to avoid the error “incorrect number of dimensions” in the R programming language.

The table of content is structured as follows:

You’re here for the answer, so let’s get straight to the examples:

 

Creation of Example Data

We’ll use the data below as basement for this R tutorial:

x <- letters[1:5]                     # Create example vector
x                                     # Print example vector
# [1] "a" "b" "c" "d" "e"

Have a look at the previous output of the RStudio console. It shows that our example data is a character vector containing five vector elements.

 

Example 1: Reproduce the Error – incorrect number of dimensions

In this example, I’ll show how to replicate the error message “incorrect number of dimensions” in R.

Let’s assume that we want to extract a subset of our vector using square brackets. Then, we might try to use a code like this:

x[1:3, 1:3]                           # Try to access two dimensions of one-dimensional vector
# Error in x[1:3, 1:3] : incorrect number of dimensions

Unfortunately, the previous R code leads to the error message “incorrect number of dimensions”.

The reason for this is that we have tried to extract two dimensions from a one-dimensional data object (i.e. a vector). Remember that the comma (i.e. “,”) within square brackets tells R that we want to specify another dimension.

So how can we debug this error message and solve this problem?

 

Example 2: Fix the Error – incorrect number of dimensions

In Example 2, I’ll explain how to deal with the error message “incorrect number of dimensions”.

To avoid this message, we simply have to specify the correct number of dimensions.

In this example, we are using a one-dimensional vector as basement. For that reason, we should only specify one dimension within the square brackets:

x[1:3]                                # Properly access values of vector
# [1] "a" "b" "c"

The previous R code works fine!

 

Video, Further Resources & Summary

If you need further info on the R programming code of this tutorial, you might watch the following video of my YouTube channel. In the video, I’m explaining the contents of this tutorial in a live session:

 

The YouTube video will be added soon.

 

In addition, you may have a look at the related articles of this website. A selection of tutorials is listed below:

 

To summarize: In this article, I have illustrated how to handle the error message “incorrect number of dimensions” in the R programming language. Let me know in the comments below, if you have further questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


43 Comments. Leave new

  • Hi there, i am having trouble getting this warning message “Error in “ozone.txt”[, c(1, 2)] : incorrect number of dimensions” when trying to unstack my ozone.txt data.

    data is read in as gardens=read.table(“ozone.txt”, header=TRUE)
    and R has correctly read in the data as two columns, $0zone, $Garden.

    For this problem, there are two gardens ‘A’ and ‘B’ with different values of ozone concentration, but I am trying to perform a t-test so would like the ozone concentrations organised under Garden type rather than two two just being 2 lists (sorry I know this is basic but I’m new to R!)

    when I use the command
    gardens1=unstack(“ozone.txt”[,c(1,2)])
    i get the warning message.

    I have used this before to unstack the data according to the 2nd column. I’m sure its simple but any guidance on the basics of unstacking is greatly appreciated.
    Thanks

    Reply
    • Hi Bea,

      Could you check the classes of your variables Ozone and Garden? You can do that by running the following line of code:

      sapply(your_data, class)

      What is the output of this line of code?

      Regards

      Joachim

      Reply
  • HELLO,
    I would like to ask how I can correct this error message of incorrect number of dimensions,

    > lakes grid no_lake <- grid[length(st_within(grid, lakes)) == 0,]
    Error in `[.default`(grid, length(st_within(grid, lakes)) == 0, ) :
    incorrect number of dimensions

    Reply
    • Hey Richard,

      Could you illustrate the data structure of the data you are using? Is grid a data.frame?

      Regards

      Joachim

      Reply
      • Hi Joachim,

        sorry for delay,
        the type data of grid, is a list,

        no_lake <- grid[lengths(st_within(grid, lakes)) == 0, ]
        Error in `[.default`(grid, lengths(st_within(grid, lakes)) == 0, ) :
        incorrect number of dimensions

        Look forward of your support, I

        Reply
        • Hey Richard,

          No problem! What’s the output when you run the following line of code?

          lengths(st_within(grid, lakes)) == 0

          It should be a vector of logical values (i.e. TRUE and FALSE).

          Regards

          Joachim

          Reply
        • Oh, and another thing I have just noticed: Does it work when you remove the comma at the end of your code?

          no_lake <- grid[lengths(st_within(grid, lakes)) == 0]

          Regards

          Joachim

          Reply
  • Hello Joachim,

    Both codes you give me, are working correctly (output are the same). the error message is solved.

    Thank you so much for your support.

    Richard/Live in Rwanda.

    Reply
  • Hello Joachim,
    I am running the following code:

    >library(mgarchBEKK)
    >library(vars)
    >data1 = ts(log(data$X))
    >data2 = ts(log(data$Y))
    >data3 = cbind(X, Y)
    >var = VAR(data3,type=c(“const”),lag.max=6,ic=”SC”)
    >bekk = BEKK(var,order = c(1, 1), params = NULL, fixed = NULL, method = “BFGS”, verbose = F)

    However, it gives me this error:
    Error in eps[, 1] : incorrect number of dimensions
    ————
    I also want to mention that for the BEKK function, the first argument should be “Data frame holding time series”. However, I do not know how I convert the VAR model to a data frame.

    Reply
  • Hello Joachim,
    I am trying to run a Dun`s correction test for the non-parametric Scheirer-ray-Hare`s test. However, I
    I have an error message about incorrect dimensions. Below is the code and what the error message says.
    DT = dunnTest( aw ~ Chunk.type , data=data, method=”bh”)
    Error in Psort[1, i] : incorrect number of dimensions
    In addition: Warning message:
    Chunk.type was coerced to a factor.
    Please how can I correct this?

    Kind regards,
    Marisa

    Reply
    • Hey Marisa,

      Unfortunately, I have never applied the dunnTest function myself. Based on the error message it seems like the data in Psort is not formatted properly.

      However, I have recently created a Facebook discussion group where people can ask questions about R programming and statistics. Could you post your question there? This way, others can contribute/read as well, and maybe you get better help there: https://www.facebook.com/groups/statisticsglobe

      Regards,
      Joachim

      Reply
  • Hi Joachim,

    I have some problem with time series plotting with regression.

    data_all1 = ts(HNE.df, start = c(2021,03),frequency = 365)
    linear.fit = tslm(data_all1~trend,data = data_all1)
    summary(linear.fit)

    however, it says Error in resid[, i] : incorrect number of dimensions

    Reply
    • Hey Mark,

      Could you illustrate the structure of your data? What is returned when you execute head(data_all1) ?

      Regards,
      Joachim

      Reply
      • Everlyne Owiro
        August 3, 2022 9:30 pm

        Hi Joachim, I have results for concentration and purity values of RNA samples that were extracted using two different methods i.e. CTAB and KIT. I’m trying to do the mean difference of, for instance concentration per protocol/method but I can’t get the exact codes for that. Previously when I run stat compare means, the output result showed that there was no significant difference in RNA concentration between the two methods although there was a very being observed difference. I know this question is basic, but because I’m new in R I’m unable to solve it. kindly, help. Thank you

        Reply
  • Hi Joachim,
    It shows that this:
    > head(data_all1)
    Time Series:
    Start = c(2021, 3)
    End = c(2021, 8)
    Frequency = 365
    Time Wo_IS_temperature_9am Wo_IS_temperature_3pm Wo_IS_humidity_9am Wo_IS_humidity_3pm
    2021.005 152 22.8 25.3 79 80
    2021.008 174 20.2 20.0 72 54
    2021.011 196 17.3 20.7 66 55
    2021.014 202 20.9 24.0 59 57
    2021.016 204 21.8 20.0 58 55
    2021.019 206 18.6 21.1 60 52
    Wo_IS_SO2 Wo_IS_NO Wo_IS_NO2 Wo_IS_OZONE Wo_IS_PM10 Wo_IS_PM2.5 Wo_IS_CO Wo_IS_cases
    2021.005 0.1 0.1 0.3 2.2 26.70000 5.536504 0.2 0
    2021.008 0.2 0.2 0.4 1.6 14.90127 5.536504 0.2 0
    2021.011 0.0 0.1 0.2 1.7 14.90127 5.536504 0.1 0
    2021.014 0.1 0.4 0.7 2.0 21.50000 5.536504 0.1 0
    2021.016 0.2 0.2 0.4 1.6 25.70000 5.536504 0.2 0
    2021.019 0.1 0.1 0.1 1.8 21.90000 6.700000 0.2 0

    But Thank you ! I have just fixed it by changing the data_all1 to one of the variables. Now I have some graphs now. Could you tell me how to fit GAM on the base of time series data?

    Sincerely,
    Mark

    Reply
  • Oi joaquin tudo bem estou com dificuldades para resolver esse erro:
    Error in x$species[, choices, drop = FALSE] :
    incorrect number of dimensions.
    Até agora fiz esse script:
    library(vegan)
    setwd(“C:/dados_zefa”)
    getwd()
    dir()
    data.frame(espc)
    data.frame(trat)
    esp1=data.frame(espc)
    trat1=data.frame(trat)

    esp2=vegdist((decostand(esp1, “total”)))
    View=esp2
    nmds=metaMDS(esp2,distance=’bray’, k=2, trymax = 100, autotransformation=F)
    nmds
    stressplot(nmds)
    escores1=scores(nmds)

    Reply
    • Hey Whita,

      Could you please execute your code line by line and let me know after which line of code the error message appears?

      Regards,
      Joachim

      Reply
      • (escores2d_dados <- scores(nmds2d_dados))
        Error in x$species[, choices, drop = FALSE] :
        incorrect number of dimensions
        é a linha do scores, quando vou plotar aparece essse erro

        Reply
        • Hi Rita,

          I’m sorry for the delayed reply. I was on a long vacation, so unfortunately I wasn’t able to get back to you earlier. Do you still need help with your syntax?

          Regards,
          Joachim

          Reply
  • Hello.
    I want to calculate sd for some specific columns. i mean e.g( 40th to 80th and 140 to 180th data) and it gives me one result(sd)
    So i should use comma. how can I handle it?

    Reply
    • Hey Fateme,

      Could you please explain your question in some more detail? Would you like to calculate the standard deviation for all those columns combined? Or would you like to get a separate result for each of the columns?

      Regards,
      Joachim

      Reply
  • edgeList<-matrix(unique(kerSet[,c("ID","KEup","KEdown",byrow=TRUE)]))
    Error in kerSet[, c("ID", "KEup", "KEdown", byrow = TRUE)] :
    incorrect number of dimensions

    Reply
    • Hey Shree,

      This is difficult to tell without seeing your data, but it seems like the byrow argument is at the wrong position. Does the following code work?

      edgeList<-matrix(unique(kerSet[,c("ID","KEup","KEdown")]),byrow=TRUE)

      Regards,
      Joachim

      Reply
    • is there any alternative to find nrow() because its showing null value even value are present

      Reply
      • Hey Shree,

        Please excuse the late response. I was on a long holiday so unfortunately I wasn’t able to reply sooner. Still need help with your code?

        Regards,
        Joachim

        Reply
  • would you please help to figure out the error

    Reply
  • Hi Joachim,

    I am having the following problem, and was wondering if you might know what to do:
    I am selecting rows from a 1000×10 matrix M in a loop.
    When I index the matrix, say with M[,i] outside of the loop, R can easily find the column or row I have indexed.
    When I index inside the loop, however, R cannot find it; if I ask it to
    “print(M,[,i])” inside the loop, it states
    “Error in M[, i] : incorrect number of dimensions”
    Please let me know why you think this is.

    Reply
  • rownames(puried_data)=example[5:nrow(example),’gene_name’]

    Error in `rownames<-`(`*tmp*`, value = c("TSPAN6", "TNMD", "DPM1", "SCYL3", :
    不能给没有维度的对象设'rownames'

    Reply
  • Hi Joachim,
    I am having trouble with a R script, getting this error message (see script below) and not being able to resolve iiiiit. Can you please help me?

    ##NMDS##
    nmds = metaMDS(data_dist, k=2, autotransform = F, distance=”bray”, tidy=TRUE)
    #stress
    nmds$stress #0.1261752, likely good for interpretation
    stressplot(nmds) # Diagram of Shepard

    ####until here everything works fine

    data_scores <- as.data.frame(scores(nmds))

    And here I get
    Error in x$species[, choices, drop = FALSE] :
    incorrect number of dimensions

    I thank you in advance!
    King regards,

    Marina (and my entire work group heh)

    Reply
    • Hi Marina,

      I have no experience with the metaMDS function. However, it seems like the output of scores(nmds) is not suitable for a data frame. Could you execute the following code and provide the output?

      scores(nmds)
       
      class(scores(nmds))

      Greetings to your work group! 🙂

      Joachim

      Reply
  • Cristina Castro
    November 21, 2022 6:10 am

    for a barplot, I keep getting incorrect number of names. Please help.

    Error in barplot.default(ISAF.ptable, names.arg = c(“full autocracy”, :
    incorrect number of names

    ##a vector of proportions to plot
    ISAF.ptable <- prop.table(table(ISAF = data.democracy$polity2.exp.ISAF, exclude = NULL))

    ISAF.ptable
    ##ISAF
    ##0 1
    ##-6 6 -5 and 5

    barplot(ISAF.ptable,
    names.arg = c(“full autocracy”, “full democracy”, “anocracy”), main = “Democracies”,
    xlab = “Democracies”,
    ylab = “Levels”, ylim = c(0,40), xlim = c(-10,10))

    Data.democracy.ptable <- prop.table(table(Data.democracy.ptable = data.democracy$polity2.exp.democracy, exclude = NULL))

    barplot(data.democracy,
    names.arg = c("Full autocracy", "Full democracy", "Anocracy"),
    main = "Values of Democracy",
    xlab = "Democracies",
    ylab = "Regime", ylim = c(-10,10))

    Reply
    • Hey Cristina,

      Could you please share the output when you run the following code?

      head(data.democracy)
       
      sapply(data.democracy, class)

      Regards,
      Joachim

      Reply
      • Cristina Castro
        November 21, 2022 6:02 pm

        This is the question,

        From the variable polity2, create a new variable called regime. The new variable regime is supposed
        to have three values: if polity2 is -6 or lower, then regime is a “full autocracy”; if polity2 is 6 or
        high, then the regime is a “full democracy”; finally, if polity2 is in between -5 and 5, regime is an
        “anocracy”. Once you created the variable regime, create a barplot showing the distribution of this
        variable.

        So far I have this,

        regime <- ("data.democracy$polity2")
        regime$aut <- ifelse(data.democracy$polity2 <= -6, "full autocracy", -5)
        regime$dem = 6, “full democracy”, 5)
        regime$ano <- ifelse(data.democracy$polity2 -5<5, "anocracy", -6<6)

        ##a vector of proportions to plot
        ISAF.ptable <- prop.table(table(ISAF = data.democracy$polity2.exp.ISAF, exclude = NULL))

        ISAF.ptable
        ##ISAF
        ##0 1 2
        ##-6 6 -5

        barplot(ISAF.ptable,
        names.arg = c("regime$aut", "regime$dem", "regime$ano"), main = "Democracies",
        xlab = "Democracies",
        ylab = "Levels", ylim = c(0,40), xlim = c(-10,10))

        data.democracy.ptable <- table(data.democracy$polity2.exp.taliban,
        exclude = NULL) / nrow(data)
        barplot(data.democracy$polity2,
        names.arg = c( "Full autocracy", "Full democracy", "Anocracy"),
        main = "Regime distribution",
        xlab = "Regime classifications",
        ylab = "polity score", ylim = c(0,40), xlim = c(-10,10))

        The output for the code head and sapply is this:

        SAPPLY:
        country year polity2 Gdp.capita
        "character" "integer" "integer" "numeric"

        HEAD:
        country year polity2 Gdp.capita
        Afghanistan 2018 -1 520.8966
        Albania 2018 9 5253.63
        Algeria 2018 2 4278.85
        Angola 2018 -2 3432.386
        Argentina 2018 9 11652.57
        Armenia 2018 7 4212.071
        Australia 2018 10 57305.3
        Austria 2018 10 51512.91
        Azerbaijan 2018 -7 4721.178
        Bahrain 2018 -10 24050.76
        Bangladesh 2018 -6 1698.263
        Belarus 2018 -7 6289.939
        Belgium 2018 8 46556.1
        Benin 2018 7 901.9541
        Bhutan 2018 7 3360.267
        Bolivia 2018 7 3548.59
        Botswana 2018 8 8258.642
        Brazil 2018 8 8920.762
        Bulgaria 2018 9 9272.629
        Burkina Faso 2018 6 731.1717
        Burundi 2018 -1 275.4296
        Cambodia 2018 -4 1512.127
        Cameroon 2018 -4 1526.876
        Canada 2018 10 46210.55
        Central African Republic2018 6 509.971
        Chad 2018 -2 730.2446
        Chile 2018 10 15923.36
        China 2018 -7 9770.847
        Colombia 2018 7 6651.291
        Comoros 2018 -3 1445.451
        Costa Rica 2018 10 12026.55
        Croatia 2018 9 14869.09
        Cuba 2018 -5 NA
        Cyprus 2018 10 28159.3
        Czech Republic 2018 9 23078.57
        Denmark 2018 10 60726.47
        Djibouti 2018 3 2050.205
        Dominican Republic2018 7 7650.073
        Ecuador 2018 5 6344.872
        El Salvador 2018 8 4058.245
        Equatorial Guinea2018 -6 10173.96
        Eritrea 2018 -7 NA
        Estonia 2018 9 22927.74
        Ethiopia 2018 1 772.3122
        Fiji 2018 2 6202.162
        Finland 2018 10 49648.15
        France 2018 9 41463.64
        Gabon 2018 3 8029.822
        Georgia 2018 7 4344.631
        Germany 2018 10 48195.58
        Ghana 2018 8 2202.312
        Greece 2018 10 20324.25
        Guatemala 2018 8 4549.01
        Guinea 2018 4 885.2512
        Guinea-Bissau 2018 6 777.9699
        Guyana 2018 7 4634.681
        Haiti 2018 5 868.2848
        Honduras 2018 7 2482.73
        Hungary 2018 10 15938.84
        India 2018 9 2015.59
        Indonesia 2018 9 3893.596
        Iraq 2018 6 5878.039
        Ireland 2018 10 78806.43
        Israel 2018 6 41614
        Italy 2018 10 34318.35
        Jamaica 2018 9 5355.583
        Japan 2018 10 39286.74
        Jordan 2018 -3 4247.769
        Kazakhstan 2018 -6 9331.047
        Kenya 2018 9 1710.51
        Kosovo 2018 8 4281.292
        Kuwait 2018 -7 34243.95
        Latvia 2018 8 18088.93
        Lebanon 2018 6 8269.788
        Lesotho 2018 8 1324.283
        Liberia 2018 7 674.2095
        Libya 2018 0 7235.028
        Lithuania 2018 10 19089.71
        Luxembourg 2018 10 114340.5
        Madagascar 2018 6 460.7528
        Malawi 2018 6 389.398
        Malaysia 2018 7 11238.96
        Mali 2018 5 901.4031
        Mauritania 2018 -2 1218.596
        Mauritius 2018 10 11238.69
        Mexico 2018 8 9698.084
        Moldova 2018 9 3189.356
        Mongolia 2018 10 4103.697
        Montenegro 2018 9 8760.692
        Morocco 2018 -4 3237.883
        Mozambique 2018 5 490.1676
        Namibia 2018 6 5931.454
        Nepal 2018 7 1025.798
        Netherlands 2018 10 53024.06
        New Zealand 2018 10 41966.01
        Nicaragua 2018 6 2028.897
        Niger 2018 5 411.6889
        Nigeria 2018 7 2028.182
        Norway 2018 10 81807.2
        Oman 2018 -8 16418.93
        Pakistan 2018 7 1472.893
        Panama 2018 9 15575.07
        Papua New Guinea2018 5 2722.605
        Paraguay 2018 9 5871.467
        Peru 2018 9 6947.257
        Philippines 2018 8 3102.713
        Poland 2018 10 15424.05
        Portugal 2018 10 23145.73
        Qatar 2018 -10 69026.47
        Romania 2018 9 12301.19
        Rwanda 2018 -3 772.9678
        Saudi Arabia 2018 -10 23219.13
        Senegal 2018 7 1521.954
        Serbia 2018 8 7233.996
        Sierra Leone 2018 7 522.8581
        Singapore 2018 -2 64581.94
        Slovak Republic 2018 10 19546.9
        Slovenia 2018 10 26234.02
        Solomon Islands 2018 8 2162.652
        Somalia 2018 5 314.5624
        South Africa 2018 9 6374.015
        South Sudan 2018 0 NA
        Spain 2018 10 30523.86
        Sri Lanka 2018 6 4102.481
        Suriname 2018 5 5950.214
        Sweden 2018 10 54111.97
        Switzerland 2018 10 82838.93
        Tajikistan 2018 -3 826.6215
        Tanzania 2018 3 1050.675
        Thailand 2018 -3 7273.563
        Togo 2018 -2 671.8407
        Trinidad and Tobago2018 10 16843.7
        Tunisia 2018 7 3446.607
        Turkey 2018 -4 9311.366
        Turkmenistan 2018 -8 6966.635
        Uganda 2018 -1 643.1397
        Ukraine 2018 4 3095.174
        United Kingdom 2018 8 42491.36
        United States 2018 8 62641.01
        Uruguay 2018 10 17277.97
        Uzbekistan 2018 -9 1532.372
        Vietnam 2018 -7 2563.821
        Zambia 2018 6 1539.9
        Zimbabwe 2018 4 2146.996

        Reply
        • It seems like the error message is caused by this line of code:

          names.arg = c( "Full autocracy", "Full democracy", "Anocracy"),

          Does it work when you create your barplot without this line (see below)? How many bars are shown in this plot?

          barplot(data.democracy$polity2,
                  main = "Regime distribution",
                  xlab = "Regime classifications",
                  ylab = "polity score", ylim = c(0,40), xlim = c(-10,10))

          Regards,
          Joachim

          Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top