Function to loop through nc_open: Calls: lapply -> FUN -> nc_open r - 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.

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)
}

Running a MCMC analysis with a new tree I made using BM, anyone know what this error would mean?

tree_mvBM <- read.nexus("C:/Users/Zach/Desktop/tree_mvBM.tre")
View(tree_mvBM)
dat <- data$Tp; names(dat) <- rownames(data)
Error in data$Tp : object of type 'closure' is not subsettable
You're trying to refer to an object called data in your global workspace, presumably a data frame. The object doesn't exist (you forgot to read it in,or you called it something else, or ... ?), so R is instead finding the built-in function data. It is trying to "subset" it (i.e. $Tp tells R to extract the element named "Tp"), which is not possible because you can't extract an element of a function. (Functions are called "closures" in R for technical reasons.)
This is one reason (probably the main reason) that you shouldn't give your variables names that match the names of built-in R objects (like I, t, c, data, df, ...). If you had called your data my_data instead the error message would be
Error: object 'my_data' not found
which might be easier to understand.
This is such a common error that there are jokes about it (image search the error message):

error using loop on custom function

I am having some trouble debugging this issue can someone please let me know where I am going wrong?
I have this simple function created that will be used on multiple dataframes to get the same information
TransCleaning <- function(df){
x <- select(df, a, b, c, d, e, f, g) %>% filter(e != "$0.00")
return(x)
}
since the names of the dataframes this function will be used on should stay the same, I could easily just hard code it but I was a loop.
so I make a list of my dataframes after making their names shorter.
files2 <- c(substr(files,5,10)
Then I try and run through this loop
for(i in 1:length(files2))
{
clean=TransCleaning(files2[i])
assign(files2[i], clean)
}
I get the following error. it has something to do with calling the files2 list because
Transclean(files2[1])
does not work either, while
Transclean(df)
works fine.
The error I am getting when I run the loop and transclean(files2[1]) is as follows:
Error in UseMethod("select_") :
no applicable method for 'select_' applied to an object of class "character"
In the function, the values of the data.frame string objects are not returned, so we can use get to do this
for(i in 1:length(files2)){
clean <- TransCleaning(get(files2[i]))
assign(files2[i], clean)
}
Though, it is better not to create objects in the global environment as it can be read directly into list and then functions can be applied on list instead of having lots of objects in global env.

R minus in row name makes name sometimes unaccessible

I have an error I cant recreate with smaller examples so I hope anyone has an idea where to look at.
The problem
As described in the code-comments: rownamesX is not found in the rownames of the matrix (But they are there of course). If I print the not-found names, something like this comes out:
hsa−miR−00
It should be
hsa-miR-00
Further, the I tested some different approaches:
Code works if I source the subscript directly in Rstudio in the console (ctrl-shift-s hotkey)
Code works if I call the function in the Console (Ctrl-Enter on the line)
Code does not work if the subscript is sourced in the main script by (Ctrl-Enter on the line)
Code does not work if the whole main.R is sourced (ctrl-shift-s hotkey)
My environment:
The data matrix
~200k elements
rownames in the form of "type-type2-number"
colnames (=samples) : "S1", "S2", ...
The call:
A main script
sources a subscript
sources a function
calls the function with the data matrix as parameter
The function:
myFunction <- function(rownamesX = c("type-type2-number")
,mat){
indexes <- which(rownames(mat) %in% rownamesX) # This is empty
mat.part <- mat[indexes, ] # therefore his is empty
resp <- mat.part[1, ] - mat.part[2, ] # therefore this yields an error
}
The mistake was quite easy:
There are more than one "-":
−
-
These two look even more equal in Rstudio than here. So I looked for the first(larger) one when the second (smaller) one was in the rowname

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