Error invalid size argument trong r là lỗi gì năm 2024
Khắc phục: Chỉnh sửa cú pháp cho đúng, ở trường này điền đúng cú pháp phải thêm 2 dấu __ “std::__gcd(a,b)”. Show
Lỗi 4: [Error] ‘p’ was not declared in this scope Nguyên Nhân: Chưa khai báo biến (biến là tên dùng trong việc khai báo và tính toán…). Khắc phục: Khai báo biến (Cấu trúc khai báo: kieudulieu tenbien). Lỗi 5: Lỗi chương trình chạy nhưng không hiện ra hàm chúng ta muốn Nguyên nhân: 1. Biến không có giá trị. 2. Thiếu dấu {} (Hàm if nếu bên trong có từ 2 câu lệnh trở lên). 3. Thiếu truyền địa chỉ dấu & Khắc phục: 1. Thay đổi biến có giá trị và chạy lại. 2. Bổ sung dấu {} 3. Thêm dấu & vào tên biến cần tuyền giá trị Lỗi 6: [Error] name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive] Nguyên nhân: Do biến i bị hủy khi ra khỏi vòng lặp. Hoặc biến i chưa khai báo kiểu dữ liệu. Khắc phục: Thêm dấu {} cho vòng lặp hoặc thêm kiểu dữ liệu cho biến i. Lỗi 7: [Error] too few arguments to function ‘ps rutgon(ps*, int)’ Lỗi 8: [Error] conversion from ‘int’ to non-scalar type ‘ps {aka phanso}’ requested Lỗi 9: [Error] conflicting declaration ‘ps n’ / khai báo xung đột ‘ps n’ Nguyên nhân: Khai 1 biến 2 kiểu dữ liệu khác nhau. Khắc phục: Xóa bớt 1 kiểu diễu liệu và thay thế tên biến khác. Lỗi 10: [Error] cannot convert ‘ps {aka phanso}’ to ‘long int’ in initialization Nguyên nhân: Khai báo sai kiểu dữ liệu. Khắc phục: Khai báo lại kiểu dữ liệu cho đúng. Lỗi 11: [Error] expected ‘}’ at end of input Nguyên nhân: Thiếu dấu }. Khắc phục: Thêm dấu } sao cho đủ số lượng. Lỗi 12: [Error] redefinition of ‘ps lonnhatmangphanso(ps*, int)’ / [Lỗi] định nghĩa lại ‘ps lonnhatmangphanso (ps *, int)’ Nguyên nhân: Xuất hiện 2 hàm giống nhau trong file Khắc phục: Xóa đi một hàm. Lỗi 13: [Error] ‘__gcd’ is not a member of ‘std’ Lỗi 14: expected declaration or statement at end of input Nguyên nhân: Thiếu bộ phận nào đó trong hàm (tuyến ở cuối đầu vào). Khắc phục: Thêm hoặc bộ sung thêm các câu lệnh. Lỗi 15: [Error] no match for ‘operator>’ (operand types are ‘ps {aka phanso}’ and ‘ps {aka phanso}’) Lỗi 16: [Error] storage size of ‘a’ isn’t known / kích thước lưu trữ của ‘a’ không được biết Nguyên nhân: Mảng a[][100] chưa khai bao kích thước đầy đủ. Khắc phục: Thêm giá trị a[100][100] cho mảng. Lỗi 17: [Error] expected initializer before ‘int’ Nguyên nhân: Thiếu một dấu, hay lệnh gì đó trước hàm int main() Khắc phục: Thêm dấu vào chỗ bị thiếu trước hàm main. Lỗi 18: [Error] invalid conversion from ‘int’ to ‘int*’ [-fpermissive] Nguyên nhân: Chưa khai báo mảng a[100] Khắc phục: Khái báo lại thành kiểu mảng Lỗi 19: [Error] invalid use of void expression Nguyên nhân: Dùng hàm void không hợp lệ Khắc phục: Điều chỉnh cách sử dụng những hàm void trong hàm main() cho đúng kiểu Lỗi 20: [Error] ISO C++ forbids comparison between pointer and integer [-fpermissive] Nguyên nhân: Không thể so sách con trỏ và số nguyên Khắc phục: Kiểm tra 2 giá trị có cùng kiểu dữ liêu hay không, nếu ý tưởng bạn đúng mà vẫn không được thì bạn hãy kiểm tra xem 1 trong 2 giá trị đã viết câu lệnh đúng hay không. If you are just starting with R, you will often encounter errors in your code which prevent it to run. I remember when I was just starting to use R, errors in my code were so frequent that I almost gave up learning this programming language. I even recall that I went back to Excel a few times to finish my analyses because I could not find what was causing the issue. Fortunately, I forced myself to continue despite the difficulties of the beginning. And today, even if I still encounter errors almost every time I write R code, with experience and practice, it takes less and less time to fix them. If you are also struggling at the beginning, rest assured, it is normal: everyone experiences some frustration when learning a new programming language (and this is the case not only with R). In this post, I highlight the 10 most common errors in R and how to fix them. Of course, errors depend on your code and your analyses, so it is impossible to cover all of them (and Google does it way better than me). However, I would like to focus on some common syntax mistakes that are frequent when learning R, and which can sometimes take a long time to be fixed before realizing that the solution is right in front of our eyes. This collection is based on my personal experience and the errors encountered by my students when I teach R. This list being non-exhaustive, feel free to comment (at the end of the post) with errors you often face when using R. For each error, I provide examples and solutions to fix them. I also mention a couple of warnings (which are, strictly speaking, not errors) at the end of the post. 1. Unmatched parentheses, curly braces, square brackets or quotesOne rather trivial but still quite frequent error is a missing parenthesis, curly brace, square bracket or quotation mark. This type of error is applicable to many programming languages. In R, for instance:
These errors are easy to detect when the code is basic, but can become much harder to spot with a more complex code, for instance:
NOT correct:install.packages(ggplot2)undefined Error in install.packages : object 'ggplot2' not found Instead, write one of the two following options:install.packages("ggplot2")install.packages('ggplot2')
### Solution
The solution of course is to simply match all opening parentheses, curly braces, square brackets and quotation marks with their closing counterparts:
mean(c(1, 7, 13))undefined [1] 7undefinedx <- 7 if (x > 10) { print("x > 10") } else { print("x <= 10") }undefined [1] "x <= 10"undefinedsummary(ggplot2::diamonds[, "price"])undefined for (i in y) { for (j in x) {
for (i in y) {
for (j in x) {
2 Also, make sure:
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
8 Note that
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
9 If you are not sure about the usage of these two functions, see more details about installing and loading a package in R. 3. Typos in function, variable, dataset, object or package namesAnother common mistake is to misspell a function, a variable, a dataset, an object or a package’s name, for example:
0
1
2
3
4
5
6
7
8
9 SolutionMake sure that you correctly spell all your functions, variables, datasets, objects and packages: Note that R is case sensitive;
for (i in y) {
for (j in x) {
23 for R!
2
3
4
5
6
8
9 If you are sure that you correctly spelled an object, a function or a dataset but you still have an error stating that “object ‘…’ is not found”, make sure that you defined your object/function/dataset before calling it! It often happens that a student asks me to come to his/her computer because he/she runs the exact same code than me, but cannot make it work. Most of the time, if his/her code is indeed exactly the same than mine, he/she simply has not executed a object/function/dataset before running the code which includes that object/function/dataset. In other words, he/she simply tries to use an undefined object or variable. Remember that writing code in a R script (contrarily to the console) does not mean it is compiled. You actually have to run it (by clicking on the Run button or using the keyboard shortcut) in order the code to be executed and used later. If you are still struggling with this, see the basics of R and RStudio. 4. Missing, incorrect or misspelled arguments in functionsMost R functions require arguments. For example, the
for (i in y) {
for (j in x) {
25. Your code will not run if you do not specify compulsory arguments, or if incorrectly specify an argument. Moreover, the result might not be what you expect if you misspell an argument:
0
1
2
3
4
5 The last piece of code does not throw an error, but the result is not what we want. SolutionTo solve these errors, make sure to specify at least all compulsory arguments of the function, and the correct ones:
6
7
8
If you do not know the arguments of a function by heart, you can always check the documentation with
for (i in y) {
for (j in x) {
34, for example:
0 5. Wrong, inappropriate or inconsistent data typesThere are several data types in R, the main ones being:
You know that some operations and analyses are possible and appropriate only with some specific types of data. For example, it is not appropriate to compute the of a factor or character variable:
1
2
5 Likewise, although it is technically possible, it makes little sense to draw a of a quantitative continuous variable because in most cases, the frequency will be 1 for each value:
4
for (i in y) {
for (j in x) {
36 function.) SolutionMake sure to use the appropriate operation and type of analysis depending on the variable(s) of interest. For example:
We now illustrate the examples in R:
5
6
7
8
9
0
1
2
3
4
5
6
7 For the interested reader, see the most common descriptive statistics in R for different types of data. Note that, as for descriptive statistics, the choice of the statistical test depends on the variable’s type. See this flowchart to help you in selecting the most appropriate statistical test depending on the number of variables and their types. An error linked to the one mentioned above is inconsistent data type. See it in practice with the following example:
8
9
0
1 As you can see, vector
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
42 sign. You know that a visualization made with ggplot2 is constructed by adding several layers:
2 SolutionFor all your graphics with ggplot2, do not forget to add a
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
x <- 7
if (x > 10) {
print("x > 10")
} else {
print("x <= 10")
}
for (i in y) {
for (j in x) {
37 of size 3 appears in the tab “Environment” (the top right panel if you use the default view of RStudio): From now on, we can use that vector simply by calling it by its name:
4
5 By no means, you can assign an object with
x <- 7
if (x > 10) {
print("x > 10")
} else {
print("x <= 10")
}
for (i in y) {
for (j in x) {
48? Actually, it is used when you want to use an equal sign. I understand that it may be abstract and confusing at the moment, so let’s suppose the following two scenarios as examples (which are the two most common cases when we use
x <- 7
if (x > 10) {
print("x > 10")
} else {
print("x <= 10")
}
x <- 7
if (x > 10) {
print("x > 10")
} else {
print("x <= 10")
}
x <- 7
if (x > 10) {
print("x > 10")
} else {
print("x <= 10")
}
[1] "x <= 10" 0 With this code, we ask whether the first element of the variablefor (i in y) { for (j in x) {
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
59 since only the third child has an age equal to 3 years.
1
2 The results show that the first, second and fifth children are girls, while the third and fourth children are not girls. If you write any of these two lines:
3 You actually overwrite the
for (i in y) {
for (j in x) {
65 variables, such that our 5 children will have an age from 1 to 5 (1 year for the first child, up to 5 years for the fifth child) and all of them will be girls.
4
5 If you do not want to use the subset function, you can also use square brackets:
6
5 As you can see in the previous examples, we do not want to assign anything. Instead, we are asking “is this variable or vector equal to something else?”. For that specific need, we use
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
71 functions, you may have faced the error “Error in [.data.frame(…) : undefined columns selected”. This occurs when R does not understand the column you want to use while subsetting the dataset. Considering the same sample of 5 children introduced earlier, the following code will throw an error:
8
9 because it does not specify the column dimension. SolutionRemember that dataframes in R have two dimensions:
and in that particular order (so row first, then column)! Since dataframes have two dimensions, R expects two dimensions when you call
[1] "x <= 10" 6[1] "x <= 10" 5 This code means that we are extracting all rows wherefor (i in y) { for (j in x) {
55 is equal to 7 (first dimension, i.e. before the comma), for all variables of the dataset (since we did not specify any column after the comma). For the interested reader, see more ways to subset and manipulate data in R. 9. Problem when importing or using the wrong data fileImporting a dataset in R can be quite challenging for beginners, mainly due to the misunderstanding about the working directory. When importing a file, R will not search for the file in all your folders of your computer. Instead, it will look only in one specific folder. If your dataset is not inside that folder, it will result in an error such as “cannot open file ‘…’: No such file or directory”: To fix this, you must specify the path to the folder where your dataset is located. In other words, you need to tell R in which folder you want it to work, hence the name working directory. Setting the working directory can be done with the
for (i in y) {
for (j in x) {
75). See more details on importing a file into R and about the working directory. Another related problem is to use the wrong file. This error is different than the previous ones in the sense that you will not encounter an error but your analyses will still be wrong. It may sound trivial, but make sure to import and use the correct data file! This is particularly the case if you have files for different points in time and which have a common structure (for example weekly or monthly data files with the exact same variables). It happened to me that I reported results for the wrong week (fortunately, without much consequence). Also, make sure that you actually use all the rows you want to include in your analyses. It happened to me that, in order to test a model (and avoid long computing times), I extracted a random sample of the original dataset, and almost forgot about this sampling when running my final analyses. It is thus a good practice to remind you to remove sampling and filters after you have tested your code (and before interpreting the final results). 10. Problem when using the $ operatorFor the last error of this top 10, I would like to focus on two related errors:
for (i in y) {
for (j in x) {
77). This is different than dataframes or matrices which are two-dimensional (i.e., rows form the first dimension and columns correspond to the second dimension). The error “$ operator is invalid for atomic vectors” occurs when we try to access an element of an atomic vector using the dollar operator (
summary(ggplot2::diamonds[, "price"])
summary(ggplot2::diamonds[, "price"])
summary(ggplot2::diamonds[, "price"])
summary(ggplot2::diamonds[, "price"])
for (i in y) {
for (j in x) {
76 operator cannot be used to extract elements in atomic vectors. Instead, we must use double brackets
summary(ggplot2::diamonds[, "price"])
[1] 7 Remember that thefor (i in y) { for (j in x) {
76 operator can be used with dataframes, so we can also fix this error by first converting the atomic vector to a dataframe, and then access an element by its name with the
summary(ggplot2::diamonds[, "price"])
summary(ggplot2::diamonds[, "price"])
summary(ggplot2::diamonds[, "price"])
[1] 7 ## object of type ‘closure’ is not subsettable Another error (which I must admit is quite obscure and confusing when learning R) is the following: “object of type ‘closure’ is not subsettable”. This error occurs when we try to subset or access some elements of a function. An example with the well-knownfor (i in y) { for (j in x) {
for (i in y) {
for (j in x) {
03 In R, we can subset lists, vectors, matrices, dataframes, but not functions. So it throws an error because it is impossible to subset an object of type “closure”, and a function is of that type:
for (i in y) {
for (j in x) {
05 Most of the times, you will not encounter this error when using a basic function such as the
for (i in y) {
for (j in x) {
85, but this dataset is not defined in the environment (because it has not been imported or created properly for instance). To understand the concept, see the following examples:
for (i in y) {
for (j in x) {
07 So far so good. Now suppose we made a mistake when creating the dataset:
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
85 is not created and thus not defined. Therefore, if we now try to access the variable
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
10 This happens because, I repeat, the dataset
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
12 WarningsWarnings are different than errors in the sense that they alert you about something, but it does not prevent you from running the code. It is a good practice to read these warnings as they may give you valuable information. There are too many warnings to mention them all, but I would like to focus on two common ones:
NAs introduced by coercionThis warning occurs when you try to convert a vector which includes at least one non-numerical value to a numeric vector:
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
30 because it could not be converted to a numeric value. Removed … rows containing non-finite values (stat_bin())This warning occurs when you use ggplot2 to draw plots. For instance:
for (i in y) {
for (j in x) {
for (i in y) {
for (j in x) {
ConclusionThanks for reading. I hope that this collection of errors prevented you from making some coding mistakes, or that it helped you in debugging your code. If you still cannot fix your error, I would recommend to read the documentation of the function (if you struggle with a function in particular), or look online for the solution. Bear in mind that if you encounter an error, it is very likely that someone else posted the answer online (Stack Overflow is usually a good resource). R has a steep learning curve, in particular if you are not familiar with another programming language. Nonetheless, with practice and time, you will make less and less coding errors, but more importantly, you will be more and more proficient in typing the right keywords in search engines, resulting in less time spent looking for the solution. As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion. |