I’m trying to run the following code in R, but I’m getting an error.
I’m not sure what part of the formula is incorrect. Any help would be greatly appreciated.
> censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 0.207 (log(DIAM93))^2
- 0.0281 (log(DIAM93))^3)
Error: attempt to apply non-function
asked May 3, 2013 at 12:30
Anand RoopsindAnand Roopsind
5512 gold badges8 silver badges11 bronze badges
3
You’re missing *
s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2
as an attempt to call a function named 0.207
…
For example:
> 1 + 2*(3)
[1] 7
> 1 + 2 (3)
Error: attempt to apply non-function
Your (unreproducible) expression should read:
censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) +
0.207* (log(DIAM93))^2 -
0.0281*(log(DIAM93))^3)
Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication …
UseR10085
6,5323 gold badges21 silver badges49 bronze badges
answered May 3, 2013 at 18:44
Ben BolkerBen Bolker
202k25 gold badges365 silver badges444 bronze badges
3
I got the error because of a clumsy typo:
This errors:
knitr::opts_chunk$seet(echo = FALSE)
Error: attempt to apply non-function
After correcting the typo, it works:
knitr::opts_chunk$set(echo = FALSE)
UseR10085
6,5323 gold badges21 silver badges49 bronze badges
answered Jun 23, 2020 at 13:07
17 авг. 2022 г.
читать 1 мин
Одна ошибка, с которой вы можете столкнуться в R:
Error: attempt to apply non-function
Эта ошибка обычно возникает, когда вы пытаетесь умножить значения в R, но забыли включить знак умножения ( * ).
В этом руководстве рассказывается, как именно справиться с этой ошибкой в двух разных сценариях.
Сценарий 1. Устранение ошибки при умножении фрейма данных
Предположим, мы создаем следующий фрейм данных в R:
#create data frame
df <- data.frame(x=c(1, 2, 6, 7),
y=c(3, 5, 5, 8))
#view data frame
df
x y
1 1 3
2 2 5
3 6 5
4 7 8
Теперь предположим, что мы пытаемся создать новый столбец, равный столбцу x, умноженному на 10:
#attempt to create new column
df$x_times_10 <- df$x(10)
Error: attempt to apply non-function
Мы получаем ошибку, потому что забыли включить знак умножения ( * ).
Чтобы устранить эту ошибку, мы должны включить знак умножения:
#create new column
df$x_times_10 <- df$x*(10)
#view updated data frame
df
x y x_times_10
1 1 3 10
2 2 5 20
3 6 5 60
4 7 8 70
Сценарий 2. Устранение ошибки в векторном умножении
Предположим, мы создаем два вектора в R и пытаемся перемножить их соответствующие элементы:
#create two vectors
x <- c(1, 2, 2, 2, 4, 5, 6)
y <- c(5, 6, 8, 7, 8, 8, 9)
#attempt to multiply corresponding elements in vectors
(x)(y)
Error: attempt to apply non-function
Мы получаем ошибку, потому что мы не включили знак умножения.
Чтобы устранить эту ошибку, мы должны включить знак умножения:
#multiply corresponding elements in vectors
(x)*(y)
[1] 5 12 16 14 32 40 54
Обратите внимание, что на этот раз ошибка не возникает.
Дополнительные ресурсы
В следующих руководствах объясняется, как исправить другие распространенные ошибки в R:
Как исправить: условие имеет длину > 1 и будет использоваться только первый элемент
Как исправить: нечисловой аргумент бинарного оператора
Как исправить: dim(X) должен иметь положительную длину
Как исправить: ошибка при выборе неиспользуемых аргументов
Содержание
- How to Solve the R Error: attempt to apply non-function
- How To Fix “Attempt to apply non-function”
- Error: attempt to apply non-function in R (2 Examples)
- Example 1: Replicate the Error – attempt to apply non-function
- Example 2: Fix the Error – attempt to apply non-function
- Video & Further Resources
- Evaluation error: attempt to apply non-function. #67
- Comments
- fuzzywuzzyR: «attempt to apply non-function» error for all the functions under FuzzMatcher, FuzzExtract and FuzzUtils classes #1
- Comments
- xcms3 — Error in x$.self$finalize() : attempt to apply non-function #288
- Comments
How to Solve the R Error: attempt to apply non-function
This error message really needs to be renamed: check for the clumsy typo. When you see this, walk through your formulas around the location of the error message. Ninety nine percent of the time you’re looking at a basic syntax issue with how you are laying out your calculations in your r code. This is a common error when you have a clumsy typo in an argument or mathematical operator.
One of your calculations, likely one which uses brackets to break up your order of operations, is missing an operator somewhere in the code. There is a significant difference in how R handles the following two statements, identical except for a single character.
- profit = units * (unit_price – unit_cost)
- profit = units (unit_price – unit_cost)
In the first example, R will solve for the calculation inside the brackets (price – cost) and multiply it by the value in the variable units. Simple math. Unfortunately, this is a massive change in the mathematical operation.
In the second example, since there is no * to identify what operation to pursue, R interprets the whole thing as a function call. Solve for the difference between price and cost and apply the function that is named units to transform the result.
Except of course, there is no function named units. But there is an object named units. So what the heck, lets apply THAT to the value in question. So a very confused variable (units) which is most definitely NOT an R function (not even close!) is suddenly “applied” (Dr. Evil air quotes) to the value we fed it.
At which point the program realizes it is trying to do completely unnatural things to an innocent little variable and throws an error: attempt to apply non-function.
SIGH. And this is why we can’t have nice things.
How To Fix “Attempt to apply non-function”
Joking aside, this one is straight forward. Look at your calculations with a fine toothed comb, paying close attention to any situation where you use brackets. Make sure you separate those bracketed items from other elements of the calculation with an appropriate operator (+, -, %, *, other operators).
If all else fails, check your function name and object method references. This is especially true if you imported an r package that overlaps with your existing r code function(s).
R needs to chill on this error message. This is basically a syntax error — a bad parenthesis or creating a conflict through the juxtaposition of an argument or expression.
Источник
Error: attempt to apply non-function in R (2 Examples)
In this R tutorial you’ll learn how to handle the error message “attempt to apply non-function”.
Table of contents:
Example 1: Replicate the Error – attempt to apply non-function
Example 1 explains how to reproduce the error “attempt to apply non-function” in R.
Let’s assume that we want to perform a mathematical operation based on the values 2 and 3. Then we might try to execute some code as shown below:
2 (3) # No function specified # Error: attempt to apply non-function
The RStudio console returns the error “attempt to apply non-function”. This is because we didn’t specify a mathematical operator or a function between the two values.
Next, I’ll explain how to solve this problem…
Example 2: Fix the Error – attempt to apply non-function
This example shows how to avoid the error message “attempt to apply non-function”.
For this, we simply have to insert a mathematical operator between our two values. In this example, we’ll use the + sign:
2 + (3) # Plus sign between values # [1] 5
No error – looks good!
Video & Further Resources
Have a look at the following video of my YouTube channel. In the video, I’m explaining the topics of this article in the R programming language.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Accept YouTube Content
Additionally, you may have a look at some other tutorials of this website. You can find a selection of tutorials below.
You learned in this tutorial how to deal with the error “attempt to apply non-function” in the R programming language. If you have additional comments and/or questions, let me know in the comments.
Источник
Evaluation error: attempt to apply non-function. #67
Thus far I cannot reproduce this in a minimal example. So instead I offer a brief error report and request guidance. Maybe this is a known problem? Or my error can be recognized by sharper eyes than mine? For what it’s worth, I use later(f, delay) successfully at several other points in my shiny app.
- shiny 1.1.0, R 3.5.1, later 0.7.3.9000, macos
- in my server function
- within observeEvent(input$addTrack, <
- myFunc
The text was updated successfully, but these errors were encountered:
I think this typically happens when your later callback tries to invoke a non-function with () . For example:
(The message is slightly different if the error is not triggered via run_now() , but instead when the console is idle.)
Thanks, @wch. I think I allowed for that possibility, checked and found it not to be the case. As a test, here are three versions of myFunc , one which makes the function call, the other two which establish that loadBedGraphTrack is a function, and that it is defined and available.
The first (my preferred call) fails with the error message attempt to apply non-function .
The second definition executes w/o error, printing «function» to the console.
The third succeeds, printing this to the console:
I’d suggest running debug(loadBedGraphTrack) or putting a browser() at the top of the function, and then step through the code.
Using options(shiny.error=recover) might also help.
browser() took me right to the problem, very similar to what you diagnosed in 2014, with a similar remedy:
Источник
fuzzywuzzyR: «attempt to apply non-function» error for all the functions under FuzzMatcher, FuzzExtract and FuzzUtils classes #1
I’m running R version 3.3.2 (64-bit), python version 2.7.12 (32-bit) on Windows 8.1 (64-bit). I have installed fuzzywuzzyR as well as corresponding python packages: fuzzywuzzy, Levenshtein
I tried the following:
s1 = ‘ It was a dark and stormy night. I was all alone sitting on a red chair.’
s2 = ‘ It was a murky and stormy night. I was all alone sitting on a crimson chair.’
init
The text was updated successfully, but these errors were encountered:
The fuzzywuzzyR package uses the reticulate package for the R-Python interface. The newer version of the reticulate package (== 0.8) includes a function py_discover_config(required_module = NULL), which shows if a specific module is installed in a python version (i.e. 2.7, 3.5) . For instance, the following appears in my R-session for the fuzzywuzzy module:
You can do the same for the other two modules, which are necessary for the fuzzywuzzyR package ,
That way you can find out if all modules are installed in your default python version.
@mlampros: Your solution works! Thank you very much.
I followed these steps:
reticulate::py_discover_config() showed me python v 3.5.3 (64-bit). However, command line start showed python v 2.7.12 (32-bit). On further investigation, I realized that a separate version of python was installed during installation of tensorflow package in R.
As a quick fix, I changed the PATH variables to python 3.5 location and used pip to install Levenshtein and fuzzywuzzy. If R instance was running during this operation, then close and reopen R.
Result:
check_availability()
[1] TRUE
matcher$Partial_ratio(string1 = «abcd», string2 = «def»)
[1] 33
I found the same issue when I used fuzzywuzzyR in another system:
reticulate::py_discover_config(required_module=»fuzzywuzzy»)
python: C:Python27python.exe
libpython: python27.dll
pythonhome: C:Python27
version: 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)]
Architecture: 32bit
numpy: C:Python27libsite-packagesnumpy
numpy_version: 1.13.0
fuzzywuzzy: C:Python27libsite-packagesfuzzywuzzy
Python directory looks fine, python package is correctly detected. However,
The fact is that I built fuzzywuzzyR on a linux OS and I didn’t encounter similar errors. However I think that the issues of the reticulate package (or issues of any package that imports the reticulate package — see the ‘Reverse imports’ or ‘Reverse suggests’) can be of advantage for you. For instance :
My guess is that you have more than one python 2.7 version on your operating system.
I’ll close the issue for now, hopefully you found a fix in the previously mentioned links.
Here’s a quick fix:
- Install Python 3.5.3 64-bit version in the other system and pointed R to this version.
- Install fuzzywuzzy and Levenshtein using pip.
- Restart R
Now check_availability shows TRUE.
I’m glad you made it work.
Hello, I am bumping into this is same issue as those above. My check_availability function returns false:
These are my reticulate returns for the Levenshtein and difflib packages:
I can import both of these packages into a Python session, so I am a bit confused as to why R cannot find them. Thanks for your work on this!
if you tried all the previous suggestions and they do not work for you then probably is something wrong with the python configuration. I faced the same problem in the past when trying to import python modules with the reticulate package. To avoid unistalling and installing python from scratch, I would suggest to also try the following (which in some cases solved the issue for me):
- run R or Rstudio as Administrator (Start > search program and files > give R or Rstudio > right click > Run as administrator
- run R from command prompt.
In my OS, for instance, R is located in C:Program FilesRR-3.4.0binx64R. Then, by opening a command prompt (console) and giving (for instance in my case),
Источник
xcms3 — Error in x$.self$finalize() : attempt to apply non-function #288
I got this error when running the following line of code:
Afterwards, when I checked bpis , it was not empty and I could even generate the desired plot.
Any idea what this error means? Does it indicate a problem with my files or is it simply a bug?
The text was updated successfully, but these errors were encountered:
I’m quite confident that it is safe to ignore this error. The x$.self$finalize() function is called just before the object is removed (by the garbage collector, I believe). At this stage all the data has already returned and your result object was generated. The problem is that I was so far unable to find where or when this error happens. It seems to be some R-internal thing and is happening randomly (that’s also why I believe it has to do with the garbage collection system of R).
In any rate. short answer is: don’t worry. Ignore the error.
I keep the issue however open to remind me to dig into this once I have more time.
Just to update on this, today, I came across this error again. But this time when executing the findChromPeaks function. Maybe this information will be useful later on when looking into the issue.
Yes, I know. Didn’t have the time to look into this. While it is annoying to have these errors popping up randomly, you can savely ignore them.
Stumbled into a slightly similar error using xcms 3.2.0.
Is the error has noting to worry about as mentioned in previous posts?
##FEATURE DETECTION
cwp ## retention time correction.
I suspect this is all related to some garbage collection related things going on in R (see also issue #305).
@luckygoh , can you reproduce the error, i.e. if you run the peak detection twice, do you get the error each time? The actual proof that this is not a problem would be if you manage to run the analysis twice, once with and once without errors and, by comparing the result objects, don’t find differences. My problem is that I can not reproduce this on my mac and also not on my linux and windows test systems.
I also believe this is not really an error and it is safe to ignore it.
I have been seeing this error a lot lately, and under different circumstances, for example when running fillChromPeaks , findChromPeaks , etc., but as @jotsetung said, it does not seem to be a problem at all. I have never seen anything strange happen to the end result under any such occasions.
I saw the same error while doing Data Trimming on a mass spec data file using the metaboanalyst package. The command is raw_data
Interesting — so it is most likely related to mzR then, because I guess metaboanalyst is not using code from xcms .
Hi @jorainer , it is definitely related to mzR, I am using mzR functionality to extract EIC’s and I see this message regularly.
On top of that, I also see differences in returned EIC values between different R environments. For example, I can run commands I use in unit test locally and generate output. That test runs OK, if I click «Run Tests» for the given file from Rstudio, but fails with devtools:test() command. Also it is passing on TravisCI, but fails in Appveyor and Github-actions. I will try to make an isolated reproducible example of this.
hi,
i got the same error during the findChromPeaks function. but then after detecting some peaks, i got this error message
any idea why and how to solve it? thanks
Can you please use register(SerialParam()) before your findChromPeaks call and try again — the error message should then hopefully be a little more self-explaining. In parallel processing error messages can be less verbose/detailed.
hi jorainer, thanks for your advice.
i did as you said, and now i got this error message. what does it mean?
The rectUnique function throws this error. rectUnique uses C-code to process the data that is passed along from R. I’ve never seen such an error before. It could mean that some unexpected values are passed to this function. It’s hard to tell what exactly caused the error — would it be possible for you to share the one file with me (or some other file where you get this error) so that I could dig more into it?
thanks for your answer, jorainer. I got this error while doing peak-picking for RP positive mode, while I didn’t get any problem for the same samples in 3 other modes. I don’t know which files (among 260 files) caused this error, either. any idea how to check that? thanks
Источник
One error you may encounter in R is:
Error: attempt to apply non-function
This error usually occurs when you attempt to multiply values in R but forget to include a multiplication (*) sign.
This tutorial shares exactly how to handle this error in two different scenarios.
Scenario 1: Resolve Error in Data Frame Multiplication
Suppose we create the following data frame in R:
#create data frame
df <- data.frame(x=c(1, 2, 6, 7),
y=c(3, 5, 5, 8))
#view data frame
df
x y
1 1 3
2 2 5
3 6 5
4 7 8
Now suppose we attempt to create a new column that is equals to column x multiplied by 10:
#attempt to create new column
df$x_times_10 <- df$x(10)
Error: attempt to apply non-function
We receive an error because we forgot to include a multiplication (*) sign.
To resolve this error, we must include a multiplication sign:
#create new column
df$x_times_10 <- df$x*(10)
#view updated data frame
df
x y x_times_10
1 1 3 10
2 2 5 20
3 6 5 60
4 7 8 70
Scenario 2: Resolve Error in Vector Multiplication
Suppose we create two vectors in R and attempt to multiply together their corresponding elements:
#create two vectors
x <- c(1, 2, 2, 2, 4, 5, 6)
y <- c(5, 6, 8, 7, 8, 8, 9)
#attempt to multiply corresponding elements in vectors
(x)(y)
Error: attempt to apply non-function
We receive an error because we did not include a multiplication sign.
To resolve this error, we must include a multiplication sign:
#multiply corresponding elements in vectors
(x)*(y)
[1] 5 12 16 14 32 40 54
Notice that no error is produced this time.
Additional Resources
The following tutorials explain how to fix other common errors in R:
How to Fix: the condition has length > 1 and only the first element will be used
How to Fix: non-numeric argument to binary operator
How to Fix: dim(X) must have a positive length
How to Fix: error in select unused arguments
In R, if you are missing mathematical operators when performing mathematical operations, you can raise the error: attempt to apply non-function. This error occurs because the R interpreter expects a function whenever you place parentheses ()
after a variable name.
You can solve this error by checking your code for missing operators and including them, for example,
3 (4 ^ 2)
becomes
3 * (4 ^2)
This tutorial will go through the error in detail and how to solve it with code examples.
Parentheses in R
We use parentheses (also known as round brackets) primarily to call a function in R. Every function call requires the use of parentheses. Therefore if you place parentheses after a variable that is not a function, the R interpreter will try to call the non-function and then raise the error: attempt to apply non-function. For example:
2()
Error: attempt to apply non-function
Example
Let’s look at an example of a program that calculates the profit made from a bakery. The formula for calculating profit is amount_sold * (price - cost)
. In this case, the bakery sold 40 cakes
price = 4.99 cost = 1.40 profit = 40(price - cost)
Let’s run the code to see what happens:
Error: attempt to apply non-function
The error occurs because we are missing the * between the two terms in the mathematical expression. Therefore R is interpreting 40(price – cost) as a function call, where the function has the name 40.
Solution
We can solve this error by putting the * between the two terms in the expression. Let’s look at the revised code:
price = 4.99 cost = 1.40 profit = 40 * (price - cost) profit
[1] 143.6
The bakery made £143.60 profit!
Summary
Congratulations on reading to the end of this tutorial! Generally, this error occurs when you put parentheses after a non-function like a number. You can solve this error by double-checking your code for missing mathematical operators.
For further reading on R related errors, go to the articles:
- How to Solve R Error: $ operator is invalid for atomic vectors
- How to Solve R error in xy.coords(x, y, xlabel, ylabel, log): ‘x’ and ‘y’ lengths differ
- How to Solve R Error in apply: dim(X) must have a positive length
Go to the online courses page on R to learn more about coding in R for data science and machine learning.
Have fun and happy researching!
Error: attempt to apply non-function in R, You’ll learn how to deal with the error notice “try to apply non-function” in this R tutorial.
Approach 1:- “Error: attempt to apply non-function” in R.
Let’s pretend we’re doing a mathematical operation with the numbers 5 and 7. Then we may try executing the following code:
How to Calculate Mean Absolute Error in R »
5 (7)
Here you can see no functions or mathematical operators not provides. Let’s run the code.
Error: attempt to apply non-function
The error “try to apply non-function” is displayed in the R console. As we know, We didn’t define a mathematical operator or a function between the two values, which is why this happened.
How to Calculate Mean Absolute Percentage Error (MAPE) in R »
Approach 2:- Fix the Error
This example demonstrates how to prevent the “try to apply non-function” error notice.
We only need to introduce a mathematical operator between our two values to do this. We’ll use the plus sign in this example:
5 + (7) [1] 12
That you see this error, double-check your code to see if all operators and functions are defined correctly.
Error in x[6, ]: subscript out of bounds »
Thanks, @wch. I think I allowed for that possibility, checked and found it not to be the case. As a test, here are three versions of myFunc
, one which makes the function call, the other two which establish that loadBedGraphTrack is a function, and that it is defined and available.
Any ideas?
myFunc <- function() loadBedGraphTrack(trackName, tbl.dhs)
myFunc <- function() print(class(loadBedGraphTrack))
myFunc <- function() print(loadBedGraphTrack)
The first (my preferred call) fails with the error message attempt to apply non-function
.
The second definition executes w/o error, printing "function"
to the console.
The third succeeds, printing this to the console:
function (trackName, tbl, deleteTracksOfSameName = TRUE)
{
if (deleteTracksOfSameName) {
removeTracksByName(trackName)
}
message <- list(trackName = trackName, tbl = jsonlite::toJSON(tbl))
session <- shiny::getDefaultReactiveDomain()
session$sendCustomMessage("loadBedGraphTrack", message)
}
<bytecode: 0x7fbcd8bc7248>
<environment: namespace:igvShiny>