if statement without an else or with an else? [closed] - r

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am having some trouble interpreting a conditional here. Which one of these approaches would be better if I wanted this condition evaluated? Some code was shared with me that used this approach:
## Option 1
k1=2
a = "k1 is less than or equal 1"
if(k1 > 1) {
a = "k1 is greater than 1"
}
print(a)
But my instinct would be do something like this:
## Option 2
if(k1 > 1) {
a = "k1 is greater than 1"
} else {a = "k1 is less than or equal 1"}
print(a)
Is there any danger to using Option 1? Basically what I am asking here is what is the best practice and is either option more rigorous?

There isn't any danger to using option 1, as it works just as fine as option 2. The else statement just gives the ability to run a piece of code only if k1 is less than or equal to 1.
In a few cases, option 2 isn't so necessary especially if you only care about the condition being true. For example,
if(today's date == birthday){
System.out.println("Happy Birthday!");
} // no need for an else statement unless you want print out "today is not your b-day"

There is not much danger in using option1 , option2 is better as it allows other people to understand the code faster/easier since it is more visible to read.Also, option1 sometimes give error on complicated codes.
But both options are fine in this case.

Related

How could I make a function thar goes trough a vector and recognizes the signs of the numbers on it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I was wondering if someone can help me with this, I need a function that goes trough a vector and recognizes the signs of the numbers inside, thats de basic idea, then I'll try to make some modifications so the function counts every number and shows something like "There are 2 positive numbers and 3 negatives"
What about the following approach (I added also functionality for zeros, remove this feature if it is not needed, or merge it with one of the other two conditions):
sign_function <- function(x){
count_pos_numbers = sum(x>0)
count_neg_numbers = sum(x<0)
count_zeros = sum(x==0)
sprintf("There are %d positive numbers, %d negative numbers, and %d zeros.", count_pos_numbers, count_neg_numbers , count_zeros)
}
I hope that I understood your question correctly.

Remove first row conditionally [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is a very simple problem and I'll probably catch flame for asking this, but I've looked everywhere and I can't find the answer... Or a different approach to my code.
I need to remove the first row of a data frame if the value of the first row and third column are equal to one.
This is what I have so far:
if (foo[1, 3] == 1) {
foo <- foo[-1, ]
}
Is there a different way to do this using only bracket subsetting (avoiding using an if statement)?
Edit:
Edited for clarity.
The code you wrote doesn't remove the first row permanently, it only prints it out. Change that with foo<-foo[-1, ]
Additionally, the code within the if-statement brackets is only one line anyway, you don't technically need them, but some like them for clarity purposes
if (foo[1, 3] == 1) foo <- foo[-1, ]

Computing the age in groovy - more realistic way [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I wrote a piece of code that generates the age more realistic to real life. I assume that we increment our age every year right when we meet the day and month of our birthday, so technically some years are longer and some are shorter, but to us people it doesn't matter. Here is the solution I came up with, I basically wanted to share my solution here, and I also appreciate if someone has a better approach to share.
def today= new GregorianCalendar()
def dob= new GregorianCalendar()
dob.set(Calendar.ERA, GregorianCalendar.AD )
dob.set(Calendar.YEAR, 1983 )
dob.set(Calendar.MONTH, Calendar.MAY )
dob.set(Calendar.DATE, 23)
userMonth=dob.get(Calendar.MONTH)
userDay=dob.get(Calendar.DATE)
todayMonth=today.get(Calendar.MONTH)
todayDay=today.get(Calendar.DATE)
if(todayMonth < userMonth && todayDay < userDay){
println today.get(Calendar.YEAR)-dob.get(Calendar.YEAR)-1
}else{
println today.get(Calendar.YEAR)-dob.get(Calendar.YEAR)
}
This is an open-ended question, so you might want to consider turning it into something less subjective.
That being said, my take would be to use joda-time, in which case you could do something like this:
import org.joda.time.DateTime
import org.joda.time.Years
def yob = new DateTime(1983, 12, 10, 0, 0).toDateMidnight()
def now = DateTime.now().toDateMidnight()
def years = Years.yearsBetween(yob, now).getYears()
println "Years: $years"
If you just want to share your code for someone else to use (which, by the way, is awesome), perhaps you want to create a gist.
[EDIT] I just created one, here
Good luck!

how to paste string in R [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to paste 4 strings together, the code is here:
urlstring<-"lee/"
code<-read.csv("D:\\list.csv",sep="\n",head=FALSE)
for(y in code){count<-1
while(count<3){
mydate<-Sys.Date()-count
filename<-paste(urlstring,mydate,"&symbol=",y,sep="")
print(filename)
count<-count+1
}
}
my question is why the output is, date is changing firstly :
lee/date=2013-11-14&symbol=1
lee/date=2013-11-14&symbol=2
lee/date=2013-11-13&symbol=1
lee/date=2013-11-13&symbol=2
but in my opinion,the result should be this,the value of code should be changed firstly:
lee/date=2013-11-14&symbol=1
lee/date=2013-11-13&symbol=1
lee/date=2013-11-14&symbol=2
lee/date=2013-11-13&symbol=2
Like #mnel said. for code = 1:2 your code yields the correct results. Note that the nested for-while loop is not needed, a vectorized solution uses less code is and is often faster:
code = rep(1:2, each = 2)
mydate = Sys.Date() - code
sprintf('lee/date=%s&symbol=%d', mydate, code)
[1] "lee/date=2013-11-14&symbol=1" "lee/date=2013-11-14&symbol=1"
[3] "lee/date=2013-11-13&symbol=2" "lee/date=2013-11-13&symbol=2"
This solution is called vectorized because when sprintf is used with vectors, the result is also a vector, without explicitily using a loop.

Conditional if selecting by pattern [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Let's say I have a data like this:
data <- as.list(c("Cb-a.csv", "Cc-a.csv", "Cd-a.csv", "Ca-e.csv"))
where C is a constant part and the letter in the real case is a pattern of letter and 2 numbers. I would like to do different things depending on which
Like:
for (n in 1:length(data)){
if ( data[[n]] == <condition> ){
cat("Do this with 'Cb-a.csv', 'Cc-a.csv', 'Cd-a.csv'\n")}
else{
cat("Do this with 'Ca-e.csv'\n")}
}
Which should be my <condition> ?
It must distinguish the order or the pattern of the data input. (Reading differences between 'Ca-e.csv' and 'Ce-a.csv' ).
In some way it must recreate the data but with a "correct pattern" to see if it fits. (But not manually)
At first I thought about a grep condition, but in this case I would just get which pattern is in data.
grepl returns a boolean vector.
if ( grepl("^C.-a.csv$", data[[n]]) ) {
cat("Do this\n")
} else {
cat("Do that\n")
}
The exact regular expression depends on the real pattern you want to match.

Resources