Error with "function" class [duplicate] - r

This question already exists:
Error: Unused arguments for function aggregate()
Closed 9 years ago.
I'm trying to run the following script:
m <- matrix(c(1,1,2,1,3,12,14,16,30,21), nrow=5, ncol=2, byrow=FALSE);
colnames(m) <-c("Group","Score");
m<-data.frame(m)
head(m)
sum1 <- aggregate(list(total_score=m$Score), by=list(group=m$Group), FUN=sum)
sum1
But, when I run the script, the console returns the following error:
Error in as.data.frame.default(x) :
cannot coerce class '"function"' into a data.frame
I haven't seen this error before.... any thoughts from anyone as to what is wrong?

You most likely overwrote one of the built in functions, like list() or sum().
One thing to note, R automatically loads a workspace called ".RData" when it starts up, and you might have saved the previously overwritten functions in that file.
Check the folder you're starting R from for any .RData files, and either delete them or rename them(They might be hidden!), so R isn't loading anything on startup.

Related

How to run the acoustic index analysis of M (Median of the amplitude envelope) for multiple files in a folder in rStudio?

I am trying to run a acoustic analysis of M for multiple files in a folder. I tried various ways with loops, but really unexperienced with writing them so struggling. However, that doesn't seem to be the problem, because the error message I'll get the error message:
"Error in inputw(wave = wave, f = f, channel) : argument "f" is missing, with no default".
When I then define f (which according to the help information is the sampling frequency of wave (in Hz). Does not need to be specified if embedded in wave.), so adding "f=48000", I receive the error message: "Error in fft(wave) : non-numeric argument"
When I run a single file out of the many, I do not have to define f at all. So I am a bit confused.
I understand that it is always more helpful adding your actual script in here, but if anyone can even help me with writing a loop for this that would be much appreciated. As mentioned before, I am very inexperience when it comes to that.
Looking forward to your answers and learn more.
Here is the code I wrote:
library(seewave) #for the package M
setwd("/Users/fiene123/Desktop/samples Sounds/August27-28_outside_Unit14_1am")
ldf <- list() # creates a list
listcsv <- dir(pattern = "*.wav") # creates the list of all the csv files in the directory
for (k in 1:length(listcsv)){
ldf[[k]] <- M(listcsv[k], plot = FALSE)
}

How to fix "unused argument" error message in R studio?

I tried to run my code like I usually do, and I got an "unused argument" error message. I have previously run the code multiple times and everything worked perfectly fine, this is the first time I have gotten an error message (I haven't changed the code). The only thing I've done different is I cleared the workspace at the end of my previous session (though I have no idea if this would actually affect it?).
Below is the code:
pacman::p_load(
rio, # importing data
here, # relative file pathways
janitor, # data cleaning and tables
lubridate, # working with dates
epikit, # age_categories() function
tidyverse, # data management and visualization
skimr,
psych,
reshape2, #for reshaping dataset
dplyr,
miscFuncs,
foreign, #read data formats
rcompanion, # group means
eeptools,
plyr)
mesh_dat <- import(here("R", "BTmeshdata.xlsx"))
The error message:
Error in here("R", "BTmeshdata.xlsx") :
unused argument ("BTmeshdata.xlsx")
The issue seems to be in how the dataset is imported because I have the same issue with importing a dataset from a different project.
.here and my folder "R" are located in my Documents folder.
Thanks!

Function to loop through nc_open: Calls: lapply -> FUN -> nc_open r

I'm trying to simplify my scripts, and therefore trying to loop through a set of netcdf-data I have. There are five I have, outside the loop this command works:
data <- nc_open('/specific_1/data.nc')
data_var <- ncvar_get(data, "var")
data_var <- data_var[50:164]
Now, trying to loop through the five sets I tried the following:
dflist <- c("1","2","3","4","5")
lapply(dflist, function(df) {
data <- nc_open(paste("'/specific_",df,"/data.nc',",sep=""))
data_var <- ncvar_get(data, "var")
data_var <- data_var[50:164]
NULL
})
I gives me the error
Error in R_nc4_open: No such file or directory
Error in nc_open(paste("'/specific_", :
Error in nc_open trying to open file '/specific_1/data.nc',
Calls: lapply -> FUN -> nc_open
Execution halted
I mean, it is fairly obvious that r won't find my file. But why? It puts the path together correctly, no (Error in nc_open trying to open file '/specific_1/data.nc')? There probably is an easy solution, but I haven't used r a lot until now so I can't think of one.
I think I see at least one thing where I'm going wrong, or that at least should be improved: Do I need to assign individual names to the commands (e.g. nc_open(paste("'/specific_",df,"/data.nc',",sep="")))? I think it shouldnt solve the problem though, if it worked it would probably just overwrite the data that was read in earlier.

Retrieving expected data.frame for testthat expectation

I'd like to test that a function returns the expected data.frame. The data.frame is too large to define in the R file (eg, using something like structure()). I'm doing something wrong with the environments when I try a simple retrieval from disk, like:
test_that("SO example for data.frame retreival", {
path_expected <- "./inst/test_data/project_longitudinal/expected/default.rds"
actual <- data.frame(a=1:5, b=6:10) #saveRDS(actual, file=path_expected)
expected <- readRDS(path_expected)
expect_equal(actual, expected, label="The returned data.frame should be correct")
})
The lines execute correctly when run in the console. But when I run devtools::test(), the following error occurs when the rds/data.frame is read from a file.
1. Error: All Records -Default ----------------------------------------------------------------
cannot open the connection
1: withCallingHandlers(eval(code, new_test_environment), error = capture_calls, message = function(c) invokeRestart("muffleMessage"),
warning = function(c) invokeRestart("muffleWarning"))
2: eval(code, new_test_environment)
3: eval(expr, envir, enclos)
4: readRDS(path_expected) at test-read_batch_longitudinal.R:59
5: gzfile(file, "rb")
To make this work, what adjustments are necessary to the environment? If there's not an easy way, what's a good way to test large data.frames?
I suggest you check out the excellent ensurer package. You can include these functions inside the function itself (rather than as part of the testthat test set).
It will throw an error if the dataframe (or whatever object you'd like to check) doesn't fulfill your requirements, and will just return the object if it passes your tests.
The difference with testthat is that ensurer is built to check your objects at runtime, which probably circumvents the entire environment problem you are facing, as the object is tested inside the function at runtime.
See the end of this vignette, to see how to test the dataframe against a template that you can make as detailed as you like. You'll also find many other tests you can run inside the function. It looks like this approach may be preferable over testthat in this case.
Based on the comment by #Gavin Simpson, the problem didn't involve environments, but instead the file path. Changing the snippet's second line worked.
path_qualified <- base::file.path(
devtools::inst(name="REDCapR"),
test_data/project_longitudinal/expected/dummy.rds"
)
The file's location is found whether I'm debugging interactively, or testthat is running (and thus whether inst is in the path or not).

read.csv() and colClasses [duplicate]

This question already has answers here:
Error in <my code> : object of type 'closure' is not subsettable
(6 answers)
Closed 8 years ago.
I am trying to use read.csv() command, but I do not understand colClasses part to run coding. Does anyone explain what it is, and also give me example of simple coding for read.csv()?
Also, if I run my coding for read.csv(), I get an error
> object of type 'closure' is not subsettable
What type of error is this? Last time I run my code, it worked, but now I get this. I am not sure what change I should make here. This is my code:
Precipfiles[1:24] <- list.files(pattern=".csv")
> DF <- NULL
> for (f in Precipfiles[1:24]) {
data[1:24]<-read.csv(f,header=T,sep="\t",na.string="",colClasses="character")
DF[1:24]<-rbind(DF,data[1:24])
}
Basically, I load all data and put them together, but I have not able to use merge() command since I am having troubles I listed above.
I think I should not use colClasses="character" because data I am using are all numeric in 200 by 200 matrix. There are 24 data files that I have to put them together.
If you have any suggestions and advise to improve this coding please let me know.
Thank you for all of your help.
You really don't need the [1:24] in every assignment, this is what is causing your problems. You are assign to a subset of a indexed vector of some description.
The error message when are trying to assign to data[1:24], without data being assigned previously (in your previous usage (which you mentioned worked), data was probably a list or data.frame you had created.). As such data is a function (for loading data associated with packages, see ?data) and the error you saw is saying that (a function includes a closure)
I would suggest something like
Precipfiles <- list.files(pattern=".csv")
DFlist <- lapply(Precipfiles, read.table, sep = '\t',
na.string = '', header = TRUE)
bigDF <- do.call(rbind, DFlist)
# or, much faster using data.table
library(data.table)
bigDF <- rbindlist(DFlist)

Resources