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)))]
}
Related
I want to calculate the moving sum with varying window sizes of 1:15.
a <- matrix(0,257,15)
b <- c(1:257)
for(j in 1:15) {
for(i in j:257) {
a[i,j] <- sum(b[i-j+1:i])
}
}
However, the above code gives cases me confusion, as it yields NA after the 129th row in every column. What could be reason for such behaviour?
Add parentheses (...):i into indexing of b[(i-j+1):i] in order to properly have a range between i-j+1 and i. The full code then reads as
a <- matrix(0,257,15)
b <- c(1:257)
for (j in 1:15) {
for (i in j:257) {
a[i,j] <- sum(b[(i-j+1):i])
}
}
As an example on the importance of the parentheses, you may compare the calculating order of the following three cases:
> (1+1):2
[1] 2
> 1+1:2
[1] 2 3
> 1+(1:2)
[1] 2 3
I'm replicating exactly same results. There must be some kind of bug (or feature unknown to me) in R engine. The expressions are correct (added "bCoordinetes" to check those). The results get fixed when closing the row expression in brackets:
a <- matrix(0,257,15)
bCoordinates <- matrix(0,257,15) #added just for validation - not needed for results
b <- c(1:257)
for(j in 1:15) {
for(i in j:257) {
a[i,j] <- sum(b[(i-j+1):i]) #closing column calc to brackets fixes the issue
bCoordinates[i,j] <- i-j+1 #added just for validation - not needed for results
}
}
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
}
}
This code is producing
Error in subset.default(sos1, grepl(m, sos1)) : 'subset' must be logical
unik contains c("900-12004-2501-000", "900-12004-2510-000", "900-12005-0120-000")
sos1 contains c("900-12004-2501-0008000FOX1 SFOX1", 900-12004-2510-0008000FOX1 SFOX1", 900-12005-0120-0008000FOX1 SFOX')
Please Help
x <- nrow(miss)
unik <- unique(miss$Material.Number)
unik1 <- as.character(unik)
sos <- read.xlsx("trprod.xlsx", sheet = 1)
sos1 <- as.character(sos$Source.of.Supply)
output <- c()
for (i in 1:x)
{
m <- (unik1[i])
result <- subset(sos1, grepl(m, sos1))
if (length(result) == 0 ){
print('in if')
output <- c(output, m)
}
}
You get the error message because your running variable i runs from 1 to nrow(miss). Your vector unik1, however is shorter than nrow(miss), due to the unique operator being applied to it. Hence, when i exceeds the length of unik1, the variable m inside your loop becomes NA and grepl returns a vector of NAs which is of class int not logical. That's where the error comes from.
You can either change x to x <- length(unik1) or - of you really need to loop over all rows of miss - change the subset operation to
result <- subset(sos1, as.logical(grepl(m, sos1)))
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.
I tried to write some functions to calculate anova power and sample size using non-central parameter.
There're some very good functions in R but my functions were to learn and reproduce line of thought from a biostatistical book...
Despite de math involved, my "nc" and "fpower" functions just work well, and as expected:
nc <- function(diff,n,sd) {
nonc <- (diff^2/2)*(n/sd^2)
return(nonc)
}
fpower <- function(k,n,diff,sd,alpha=0.05) {
nonc <- nc(diff,n,sd)
dfn <- k - 1
dfd <- k*(n-1)
f1 <- qf(1-alpha,dfn,dfd)
f2 <- pf(f1,dfn,dfd,nonc)
return(1-f2)
}
However, my "fsample" just doesn´t work as expected. Return 2, the first n in the seq.
fsample <- function(k,diff,sd,alpha=0.05,power=0.9){
for(n in 2:5000){
if ( fpower(k,n,sd,alpha) >= power) break
}
return(n)
}
But, if I "hand" run this code in console it work as expected!!
And return the right n value.
What's wrong?
You didn't pass the diff argument to fpower, so the arguments aren't in the order you think they are. fsample should be:
fsample <- function(k,diff,sd,alpha=0.05,power=0.9){
for(n in 2:5000){
if ( fpower(k,n,diff,sd,alpha) >= power) break
}
return(n)
}
Note that this wouldn't have been a problem if you had named the arguments when you called fpower because you would have received an error about diff being missing and not having a default value:
# this will error
fsample <- function(k,diff,sd,alpha=0.05,power=0.9){
for(n in 2:5000){
if ( fpower(k=k,n=n,sd=sd,alpha=alpha) >= power) break
}
return(n)
}
Also, you might want to avoid giving data objects the same name as functions (e.g. diff, sd, and power are also functions), otherwise you may confuse yourself.