R: Object not found within a function - r

I'm having some issue with my code, whenever I run the code the output is always comes back with an error saying "Object pv not found" can anyone help out? It'd be greatly appreciated!
Code:
lo <- function(x, y)
{
for(i in 1:(y-1))
{
for(j in 1:length(x))
{
First = function (x)
{if (i%%x[j] == 0) {pv <- cumsum(x)}}
}
}
return(pv)
}
lo(6, 20)

The problem is that your inner loop goes from 1:length(x).
You are supplying 20 as x. The length of an object that contains one number is 1. Looping from 1 to 1 means 0 iterations. You never run pv <- cumsum(x) then. So pv isn't defined when you get to the return statement.

Related

R markdown "argument is of length zero"

Code is running fine in R, but getting an "argument is of length zero" error when I run in R Markdown. Just running a loop to split a probability output into 0 or 1 at 50%.
Looked through some similar posts but didn't find anything about issues when moving to markdown.
for (i in 0: (nrow(test)-1)){
i <- i+1
if (test$pred_basemodel[i] < 0.5){
test$pred_basemodel[i] <- 0
}
else {
test$pred_basemodel[i] <- 1
}
}
Thanks for any suggestions!
I think you can remove i <- i+1 in the for loop, since i is the iterator which will run through 1:nrow(test) automatically. Also, you can use 1:nrow(test) instead of 0:(nrow(test)-1) as the for loop condition, since your indexing naturally starts from 1.
You can try the code below
for (i in 1:nrow(test)){
if (test$pred_basemodel[i] < 0.5){
test$pred_basemodel[i] <- 0
}
else {
test$pred_basemodel[i] <- 1
}
}

R for loop returns NULL instead of expected values

i<-c(1:44)
diff_arbeitnehmer <- for(x in i){if(x == 44) {diff_arbeitnehmer[x] <- 0} else{diff_arbeitnehmer[x] <- 100/erwerbstaetige[x,2]*erwerbstaetige[x,4]-100/erwerbstaetige[x+1,2]*erwerbstaetige[x+1,4]}}
My data frame has 44 entriess
I am using R script could someone tell me what could be the reason?
I am lost with this
I can't run your code because I don't have your data frame, but maybe the reason is because you are trying to assing a for loop into the variable diff_arbeitnehmer. I did this change and hope that know it works:
i<-c(1:44)
diff_arbeitnehmer <- c()
for(x in i){
if(x == 44){
diff_arbeitnehmer[x] <- 0
} else{
diff_arbeitnehmer[x] <- 100/erwerbstaetige[x,2]*erwerbstaetige[x,4]-100/erwerbstaetige[x+1,2]*erwerbstaetige[x+1,4]
}
}
An advice is to take a look if the assignment in the last condition is right, maybe you need to put some parenthesis.

Function raise error with return statement

I want to process a own designed function on every cell using the calc function of the "raster" package.
Everything works perfectly when I try to print the "final" result of the function (value I want to return), but when I try to use return statement, I got an error :
Error in .local(x, values, ...) :
values must be numeric, integer or logical.
Here is the code leading to that error
inR <- 'D://test/TS_combined_clipped.tif'
outR <- 'D://test/R_test3.tif'
rasterB <- brick(inR)
fun1 <-function(x){
years = seq(1, 345)
na_idx = which(is.na(x))
years = years[-na_idx]
x <- na.omit(x)
idx = detectChangePoint(x, cpmType='Student', ARL0=500)$changePoint
return(years[idx]) # this raises error
# print(years[idx]) # This does *not* raises any error
}
r <- calc(rasterB, fun=fun1, filename=outR, overwrite=TRUE)
How is it possible to have a return statement to make it fails ?
Some of my tests leads to the fact that it seems that the process fails just after the execution of the calc function on the very last cell of the rasterBrick.
But I have no clue of where to start to try to fix this.
Input image is available here
[EDIT]
I just noticed that if I use return(idx) instead of return(year[idx]) the process works without error raised.
So it seems that the problem is more at fetching the value of the year variable.
Is therefore any particular thing that I missed in the use of indexes with R ?
Comment of user2554330 put me on the good track, issue was that calc cannot handle a "numeric(0)" result.
Updated code is then
inR <- 'D://test/TS_combined_clipped.tif'
outR <- 'D://test/R_test3.tif'
rasterB <- brick(inR)
fun1 <-function(x){
years = seq(1, 345)
na_idx = which(is.na(x))
years = years[-na_idx]
x <- na.omit(x)
idx = detectChangePoint(x, cpmType='Student', ARL0=500)$changePoint
if (idx==0){
return(0)
} else {
return(as.integer(years[idx]))
}
}
r <- calc(rasterB, fun=fun1, filename=outR, overwrite=TRUE)

Why would this 'sapply' function in R return an invalid response given my function?

CountNew <- function(x){
if (x==0) y <- 1
return(y)
}
allCF$NewECount >- sapply(allCF$Count, CountNew)
Using the above code, if a value in EquipCount in allCF is currently equal to 0, I want to change it to 1 while keeping the other values the same, then maintain the values of the rest of the values not equal to 0. I made sure these were numbers (not factors) through the str(rawCF) command
But then I get the following error:
Error in FUN(X[[i]], ...) : object 'y' not found
What is causing this problem?
The code logic is wrong.
What if the element does not satisfy x==0? The function will return a y which is not defined. Add one line will solve it:
Solution 1
allCF <- data.frame(Count=c(0,0,-1))
CountNew <- function(x){
y=x
if (x==0) y = 1
return(y);
}
allCF$NewECount <- sapply(allCF$Count, CountNew)
Solution 2: Vectorize your CountNew function
allCF <- data.frame(Count=c(0,0,-1))
CountNew <- Vectorize(function(x){
if (x==0) return(1);
return(x);
}
)
allCF$NewECount <- sapply(allCF$Count, CountNew)
Now you may do CountNew(allCF$Count) directly.

Write a function in R to find perfect numbers

I am a beginner in R and am attempting the following question:
Create a function in R which takes as its
input a natural number N and returns as an output the list of
all perfect numbers between 1 and N.
There are 3 steps here:
1. Check the list of factors
2. Check whether it is a perfect number
3.check from 1 to 10000
factorlist<-function(n){
if(n<2){return("Invalid Input")}
if(n%%1!=0){return("Invalid Input")}
vec<-0
for(i in 1:(n-1)){
if(n%%i==0){
vec[length(vec)]<-i
vec<-c(vec,0)
}
}
vec<-vec[-length(vec)]
return(vec)
}
perfectcheck<-function(n){
if(n-sum(factorlist(n)) ==0) {return("Perfect Number")}
else{return("Not Perfect Number")}
}
perfectcheckN<-function(N){
for(i in 1:N){
if(perfectcheck(i)=="Perfect Number"){
vec[length(vec)]<-i
vec<-c(vec)
}
}
vec<-vec[-length(vec)]
return(vec)
}
and i got the following error for my third step
Error in sum(factorlist(n)) : invalid 'type' (character) of argument
I spent like few hours and still could not figure out my mistake, please help. Thanks!
The output of factorlist(i) is character when i==1.
There's a lot of loops and ifs in your code. You can just do
facs <- function (x) {
x <- as.integer(x)
div <- seq_len(abs(x) - 1L)
div[x%%div == 0L]
}
perfectcheckN <- function(N){
out <- 1:N
out[sapply(out, function(x) x == sum(facs(x)))]
}

Resources