If & ifelse statement in R - r

As the new user in R, I met few problems when I tried to evaluate a.
Code:
// time2 are numbers //
a = d3$Time2
b = c(...)
for (i in 1:65){
for (j in 1:1762){
if( (a[j]>=1474161415+900*(i-1))&(a[j]<1474161415+900*i) ){ a[j] = b[j] }
}
}
Results:
Error in if ((a[j] >= 1474161415 + 900 * (i - 1)) & (a[j] < 1474161415 + :
missing value where TRUE/FALSE needed
Also I have tried:
ifelse( ((a[j]>=1474161415+900*(i-1)) & (a[j]<1474161415+900*i)) , a[j]=b[j])
Results:
-unexpected '=' in -ifelse( ((a[j]-=1474161415+900-(i-1)) &
(a[j]-1474161415+900-i)) , a[j]=--

Related

R studio "Error in if missing value where TRUE/FALSE needed" and warning "In if (col.names) d[[2L]] else NULL"

I have a huge dataset with multiple columns representing the expression of a given gene in a specific tissue. The dataset is as follows with 74,440 genes:
I am trying to look for genes that have a very specific expression pattern and hence I am using multiple && operators in the if command in the code below. So essentially I am trying to find the genes that match the exact values I put in the if command. Any genes that match this criteria will be appended into a new file which is called Ovaries_only.
The data sample provided is exactly how the excel file looks and there are a lot more rows than showed. I am trying to see if the value in the 18th column exceeds 100 while the rest of the columns are lower than a set value. Based on this I am trying to append the entire row that fits the criteria into a new file.
As I run the code, I keep getting the error ""Error in if missing value where TRUE/FALSE needed" and also multiple warnings "In if (col.names) d[[2L]] else NULL :
the condition has length > 1 and only the first element will be used"
Could you tell me what I am doing wrong.
counter = TRUE
i = 1
while (counter == TRUE) {
if( (data[i,3] < 10) && (data[i,4] < 10) && (data[i,5] < 10) && (data[i,6] < 5) && (data[i,7] < 5) &&
(data[i,8] < 5) && (data[i,9] < 5) && (data[i,10] < 5) && (data[i,11] < 5) && (data[i,12] < 5) &&
(data[i,13] < 5) && (data[i,14] < 5) && (data[i,15] < 5) && (data[i,16] < 5) && (data[i,17] < 5) && (data[i,18] > 100) && (data[i,19] < 50) ){
df = data[i, ]
write.table(df, "ovaries_only.csv", sep = ",", row.names = FALSE, col.names = !file.exists("ovaries_only.csv", append = TRUE))
i = i + 1
if (i == 74440){
counter == FALSE
}
}
else{
i = i+1
if (i == 74440){
counter == FALSE
}
}
}

KnapSack dynamic programming in R with recursive function

I created this simple code in R to solve the Knapsack program with a recursive funtion
n <- c(0,1,2,3,4)
v <- c(10,40,30,50)
w <- c(5,4,6,3)
k <- 10
myfunction <- function(n,k){
if (n==0 | k==0){
output <- 0
} else if (w[i] > k) {
output <- myfunction[i-1,w]
} else {
output <- max(v[i]+ myfunction(i-1, k-w[i]),myfunction(i-1,k))
}
return(myfunction)
}
However, I don't get a value as an output, but the whole function. For example if I put in:
myfunction(4,10)
I don't get an value of 90, but the whole funtion typed out.
these are the values
There were several errors beyond the ones pointed out by #etienne. Here's an annotated debugging session. First we fix the returned object:
> myfunction <- function(n,k){
+ if (n==0 | k==0){
+ output <- 0
+ } else if (w[i] > k) {
+ output <- myfunction[i-1,w]
+ } else {
+ output <- max(v[i]+ myfunction(i-1, k-w[i]),myfunction(i-1,k))
+ }
+ return(output)
+ }
> myfunction(4,10)
Error in if (w[i] > k) { : argument is of length zero
Obviously neither w nor k are of length zero which suggests it must be i. (As also pointed out by etienne). Looking at your code it appears you actually intended i to be the index that decreased until the terminating condition was met. So replace n by i in the few instances where it appeared:
> myfunction <- function(i,k){
+ if (i==0 | k==0){
+ output <- 0
+ } else if (w[i] > k) {
+ output <- myfunction[i-1,w]
+ } else {
+ output <- max(v[i]+ myfunction(i-1, k-w[i]),myfunction(i-1,k))
+ }
+ return(output)
+ }
> myfunction(4,10)
Error in myfunction[i - 1, w] :
object of type 'closure' is not subsettable
So you also made the mistake of using square-brackets where parentheses (aka bracket in the non-US sections of the world) were needed:
> myfunction <- function(i,k){
+ if (i==0 | k==0){
+ output <- 0
+ } else if (w[i] > k) {
+ output <- myfunction(i-1,w)
+ } else {
+ output <- max(v[i]+ myfunction(i-1, k-w[i]),myfunction(i-1,k))
+ }
+ return(output)
+ }
> myfunction(4,10)
[1] 90
Success, well, almost. Most of the warnings are because you used | instead of || in one of the conditionals:
Warning messages:
1: In if (i == 0 | k == 0) { :
the condition has length > 1 and only the first element will be used
2: In if (w[i] > k) { :
the condition has length > 1 and only the first element will be used
3: In if (i == 0 | k == 0) { :
the condition has length > 1 and only the first element will be used
4: In if (i == 0 | k == 0) { :
the condition has length > 1 and only the first element will be used
5: In if (i == 0 | k == 0) { :
the condition has length > 1 and only the first element will be used
6: In if (i == 0 | k == 0) { :
the condition has length > 1 and only the first element will be used
So replace that instance with a logical ||. To deal with the other warning that didn't seem to sabotage your logic, realize that w[i] is length-0 when i == 0, so add a logical clause in the conditional that first tests for that possibility and use the correct "double-AND-sign" ( && ):
myfunction <- function(i,k){
if (i==0 || k==0){
output <- 0
} else if (length( w[i]) && w[i] > k) {
output <- myfunction(i-1,w)
} else {
output <- max(v[i]+ myfunction(i-1, k-w[i]), myfunction(i-1,k))
}
return(output)
}
Now you get:
> myfunction(4,10)
[1] 90

MATLAB to R Conversion: Append values to an existing empty array through for loop

I have the below code with me. This code was written originally in MATLAB. I have two questions here:
1) What would be the corresponding command in R for the below command in MATLAB:
duet(i).p = [];
2) In the below code I am getting all the correct 6 values for duet$n, but I am not getting correct values for duet$p. My question is how to append the values to an empty existing array duet$p[i] in R through the for loop iterations.
This line is not working in the below code:
duet$p[i] <- c(duet$p[i],j)
I might also have declared duet$p[i] <- array() incorrectly.
The values for duet.n and duet.p from MATLAB are:
duet.n
2 0 2 0 1 3
duet.p
[] [3,6] [] [1,3,5,6] [1,6] []
In R, I am getting duet$n values correctly, but I am not able to get the array kind of results for duet$p.
Any help to get the duet$p values would be appreciated.
x <- matrix(c(-1,2,4,1,7,4.2,3,0,1.2,-1.2,5.1,4,2,3.1,1.1,1,1,9,0,1,2,2,8,1,2,2,2,2,2,2),nrow=6,ncol=5,byrow=T)
fro=1;N=6;M=2;V=3;
F <- list(f=c())
duet = list()
for (i = 1 : N){
duet$n[i] = 0
duet$p[i] = array() ## Create an empty array
for (j in 1 : N){
dl = 0
de = 0
dm = 0
for (k = 1 : M){
if (x[i,V + k] < x[j,V + k]){
dl = dl + 1
} else if (x[i,V + k] == x[j,V + k]){
de = de + 1
} else{
dm = dm + 1
}
}
if (dl == 0 & de != M){
duet$n[i] = duet$n[i] + 1
} else if (dm == 0 & de != M){
duet$p[i] = c(duet$p[i],j)
}
}
if (duet$n[i] == 0){
x[i,6] = 1
F$f = c(F$f,i)
}
}
This appears to get the output you want:
x <- matrix(c(-1,2,4,1,7,4.2,3,0,1.2,-1.2,5.1,4,2,3.1,1.1,1,1,9,0,1,2,2,8,1,2,2,2,2,2,2),nrow=6,ncol=5,byrow=T)
fro=1;N=6;M=2;V=3;
F <- list(f=c())
duet = list(n=rep(0,N), p=lapply(1:N, function(x)c()))
for (i in 1 : N){
duet$n[i] = 0
#duet$p[[i]] = c() ## Create an empty array
#if(i==2) browser()
for (j in 1 : N){
k=1:M
dl <- sum(x[i,V + k] < x[j,V + k])
de <- sum(x[i,V + k] == x[j,V + k])
dm <- sum(x[i,V + k] > x[j,V + k])
if (dl == 0 & de != M){
duet$n[i] = duet$n[i] + 1
} else if (dm == 0 & de != M){
duet$p[[i]] = c(duet$p[[i]],j)
}
}
if (duet$n[i] == 0){
#x[i,6] = 1
F$f = c(F$f,i)
}
}
What have I done?
commented out the line x[i,6] =1, because there isn't an x[i,6], and I'm not sure what you meant it to be. You will need to sort this out.
Initialised duet$n as a vector
Initialised duet$p as a list of n empty vectors
removed the k loop as conditional counting in R can be done as the sum of elements where the condition is TRUE.
corrected the syntax of for loops: = became in
I think you're trying to do duet[i]$p instead of what you're doing. Also you need to initialize each cell as a list

Break / exit from nested blocks in R without printing error messages

I've been writing an R script that would simulate outbound phone calls from a call center to demonstrate the rules ( if the call counts exceeds 5 OR if the call is a success OR a call back request is set then the code should exit). If I use break statement, I'm not getting the desired result, as a workaround I'm using the stop function. Is there a way to print a message and stop executing a function without throwing an Error ?
This is my code:
dial <- function(callcount = 1)
{
maxcalls <- 5
# Possible Outcomes
outcomes <- c("RPCON","WPCON","CBLTR")
# Probaility Vector for results:
pvector <- c(1,1,1)
repeat{
if(callcount == 5){
stop("5 attempts reached, closing record for the day")
}
res <- sample(outcomes, 1, prob=pvector, rep = TRUE)
print(paste0("Attempt ",callcount))
if(res == "RPCON" & callcount <= 5){
print("Call Successful")
stop(simpleError("Ended"))
}else if(res == "WPCON" & callcount <= 5){
print("Wrong Party!, Trying alternate number...")
callcount <- callcount + 1
dial(callcount)
}else if(res == "CBLTR" & callcount <= 5){
print("Call back request set by agent")
stop("Ended")
}
}# End of REPEAT loop
}# End of function
Any help is appreciated.
I would suggest to use a While loop with a boolean to check if you want to continue to loop :
dial <- function(callcount = 1)
{
maxcalls <- 5
# Possible Outcomes
outcomes <- c("RPCON","WPCON","CBLTR")
# Probaility Vector for results:
pvector <- c(1,1,1)
endLoop <- FALSE
while(callcount <=5 & endLoop == FALSE ){
if(callcount == 5){
stop("5 attempts reached, closing record for the day")
}
res <- sample(outcomes, 1, prob=pvector, rep = TRUE)
print(paste0("Attempt ",callcount))
if(res == "RPCON" & callcount <= 5){
print("Call Successful")
endLoop <- TRUE
}else if(res == "WPCON" & callcount <= 5){
print("Wrong Party!, Trying alternate number...")
callcount <- callcount + 1
dial(callcount)
}else if(res == "CBLTR" & callcount <= 5){
print("Call back request set by agent")
endLoop <- TRUE
}
}# End of REPEAT loop
}# End of function
Hope this helps.

if-else statement inside for loop for R

I've read through some of the if-else if question for for loop, but I cannot seem to solve what the problem is for my script.
type = numeric(length(r))
for (i in 1:10) {
if ( ((s_mov[i] < s_rot[i]) & (e_rot[i] < e_mov[i])) | ((s_rot[i] < s_mov[i]) & (s_mov[i] < e_rot[i])) == TRUE) {
type[i]=1
}
else if ( ((s_doc[i] < s_rot[i]) & (e_rot[i] < e_doc[i]) == TRUE) {
type[i]=2
}
else if ( ((s_rot[i] < e_mov[i]) & (s_doc[i] < e_rot[i])) | ((s_rot[i] < s_mov[i]) & (s_doc[i] < e_rot[i])) == TRUE) {
type[i]=3
}
}
or I've tried this way as well
for (i in 1:10) {
if ( ((s_mov[i] < s_rot[i]) & (e_rot[i] < e_mov[i])) | ((s_rot[i] < s_mov[i]) & (s_mov[i] < e_rot[i])) == TRUE) {
type[i]=1
}
else if ( ((s_doc[i] < s_rot[i]) & (e_rot[i] < e_doc[i]) == TRUE) {
type <- replace(type, type[i],2
}
else if ( ((s_rot[i] < e_mov[i]) & (s_doc[i] < e_rot[i])) | ((s_rot[i] < s_mov[i]) & (s_doc[i] < e_rot[i])) == TRUE) {
type <- replace(type, type[i],3
}
}
but I'm constantly getting
Error: unexpected '{' in:
What's wrong?
I'm not sure but I think depending on the data, when all 1:10 satisfy first if statement, it writes 1 for all 10 elements, and rather than stooping, it continues and cause error.
It looks like you're missing several closing brackets in different places. I highly recommend using a good IDE, such as RStudio, which has a side-benefit of highlighting the matching brackets.
Both the type <- replace... statements need a closing ).
Just by eyeballing, it looks like the first else if is missing a closing ) as well:
else if ( ((s_doc[i] < s_rot[i]) & (e_rot[i] < e_doc[i]) == TRUE) {
you have 4 opening and only 3 closing brackets in there.
I haven't checked the other statements, but you should.
In the first example, your first else if has an extra (.
In the second example, your first else if has an extra (, and your replace functions have no ).

Resources