jeudi 2 janvier 2020

How to delete from vector using ifelse condition in R

I have a vector a with values (1,2,3,4) and another vector b with values (1,1,0,1). Using the elements in b as a flag, I want to remove the vector elements from A at the same positions where 0 is found in element b.

  a <- c(1,2,3,4)
  b <- c(1,1,0,1)
     for(i in 1:length(b))
  {
    if(b[i] == 0)
    {
      a <- a[-i]
    }
  }

I get the desired output

a [1] 1 2 4

But using ifelse, I do not get the output as required.

    a <- c(1,2,3,4)
  b <- c(1,1,0,1)
    for(i in 1:length(b))
    {
      a <- ifelse(b[i] == 0,a[-i],a)
    }

Output:

a [1] 1

How to use ifelse in such situations?

mercredi 1 janvier 2020

Can't I use many ifelse in else?

This code is a complex if. I write this code because I want to use the flow control to decide whether the user can eat the cake or not. The variables a, b, c, d are some indexes that the user will put in. In this place, I have already set these indexes. Based on the indexes, the nested if will give some responses.

a <- 1 ; b <-  2 ; c <- 3 ; d <- 3

index <- sum(a, b, c, d)

if(index > 11){print("enjoy the cake right now!")
}else{
  if(b == 1 | c == 1){"You don't have the right to eat cake."
  }else{
    ifelse(b == 3, "go to ATM and take money right now", 
           ifelse(b == 2, "use the budget of tomorrow first",print("") )
    )
    print("bb")
    ifelse(c == 4, "run to the cake store and burn some calores ", 
           ifelse(c == 3,"ride youbike to the cake store", 
                  ifelse(c == 2, "ride youbike to the cake store",print(""))))
    print("aa")
    }
        }

My expectation is:

[1] "use the budget of tomorrow first"
[1] "bb"
[1] "ride youbike to the cake store"
[1] "aa"

But the result is:

[1] "bb"
[1] "aa"

Why the R program didn't run the "ifelse" part and just printed "bb", "aa"? Is this because the "else" can't include "ifelse"?

Google Sheets ArrayFormula Solution for Multiplying 2 Columns, One of Which Is a Column of Lists of Numbers

I have 2 columns of inputs (A and B) and 1 column of output (C) with the number of rows unknown at design time. Each row’s inputs and outputs are independent; row 1 cannot affect row 2.

  • Column A consists of 2 possible types: a positive integer or a list of positive integers delimited by semicolons (“;”).
  • Column B consists of only a positive integer.
  • Column C is the total of column A multiplied by column B.

This is the basic formula I have devised for column C: =IF(NOT(ISBLANK($A2)),IF(ISNUMBER($B2),$A2*$B2,$B2*SUM(SPLIT($A2,"; ")))),""). And it works by filling the formula downwards, but the SUM being there makes it incompatible with ARRAYFORMULA. For robustness (because I cannot count on the users to autofill the cells themselves nor to avoid wreaking havoc on the formulae I’ve carefully laid down), I would like an ARRAYFORMULA-based solution which I can tuck inside of one protected cell in column C.

The current result using the non-ARRAYFORMULA solution:

Table of example inputs and outputs

The first 4 rows are just simple multiplication, which ARRAYFORMULA has no trouble doing. The last filled row represents (15+20+25)*1=60 which I could not do as an ARRAYFORMULA.

I have found one similar question which—unfortunately—does not apply to my case because the final solution does not use ARRAYFORMULA: sum comma delimited string of integers

I would like to create a function that compares the hours from moment to a set of div classes (new to coding sorry if this is worded incorrectly)

I can get this to work creating many if statements by stating if moment.... === 12(example below) but I would like to consolidate it to one by pulling from my div classes labeled 9, 10, 11, 12, 1, 2, 3, 4, 5

`function hourTrack() {
 if (moment().hour() === 12)
 $(".12").css("background-color", "red");
 $( ".1, .2, .3, .4, .5,").css("background-color", "blue");
}` 

My thought process leads me to believe it should be something like

function hourTrack() { if (moment().hour() === parseInt(the div id number) }

Am I on the right track? Any help appreciated!

The if statement takes what kind of objects?

In the following code we have if self.frames, but self.frames is a list. What does that mean?

import tkinter as tk
from PIL import Image, ImageTk
from itertools import count

class ImageLabel(tk.Label):
    '''a label that displays images, and plays them if they are gifs'''
    def load(self, im):
        if isinstance(im, str):
            im = Image.open(im)
        self.loc = 0 
        self.frames = []

        try:
            for i in count(1):
                self.frames.append(ImageTk.PhotoImage(im.copy()))
                im.seek(i)       
        except EOFError:    
            pass

        try:
            self.delay = im.info['duration']
        except:
            self.delay = 100

        if len(self.frames) == 1:
            self.config(image=self.frames[0])
        else:
            self.next_frame()

    def unload(self):
        self.config(image=None)
        self.frames = None

    def next_frame(self):
        if self.frames:
            self.loc += 1
            self.loc %= len(self.frames)
            self.config(image=self.frames[self.loc])
            self.after(self.delay, self.next_frame)

root = tk.Tk()
lbl = ImageLabel(root)
lbl.pack()
lbl.load("name_of_image.gif")
root.mainloop()

No Notified Errors But The Code Doesn't Perform As Instructed

Still in the early beginning stages of constructing various problems that can be solved with if-statements. One in particular that I am solving right now is a grading system in which the user inputs a number grade and the output is given showing their corresponding letter grade. There are no errors but it doesn't output the corresponding letter grade from my input.

            string goodGrade = "A";
            string okGrade = "B";
            string fairGrade = "C";
            string passGrade = "D";
            string failGrade = "F";
            string perfectGrade = "A+";
            int minGrade = 0;
            int maxGrade = 100;
            string inputLetterGrade;
            int inputNumberGrade;
            int studentA, studentB, studentC, studentD, studentE;
            int averageNumberGrade;
            string averageLetterGrade;
            studentA = 95;
            studentB = 84;
            studentC = 36;
            studentD = 72;
            studentE = 51;

            Console.Write("Insert Number Grade: ");
            inputNumberGrade = Convert.ToInt32(Console.ReadLine());

            if (inputNumberGrade == maxGrade) {
                Console.WriteLine("perfect you got an {0}", perfectGrade);

                if (inputNumberGrade <= 99 || inputNumberGrade >= 80)
                {
                    Console.WriteLine($"You got an {goodGrade}");

                    if (inputNumberGrade <= 79 || inputNumberGrade >= 70)
                    {
                        Console.WriteLine($"You got a {okGrade}");

                        if (inputNumberGrade <= 69 || inputNumberGrade >= 60)
                        {
                            Console.WriteLine($"You got a {fairGrade}");

                            if (inputNumberGrade <= 59 || inputNumberGrade >= 50)
                            {
                                Console.WriteLine("Poor performance, you got a {0}", passGrade);

                                if (inputNumberGrade >= 40 || inputNumberGrade <= 49)
                                {
                                    Console.WriteLine($"You fail, you got an {failGrade}");
                                }

                                else if (inputNumberGrade < 40 && inputNumberGrade != 0)
                                {
                                    Console.WriteLine($"You fail, you got an {failGrade}");
                                }

                                if ((inputNumberGrade != 0) == (inputNumberGrade == maxGrade))
                                {
                                    //Re-enter score to reflect whether or not the end-result is a positive or negative letter grade
                                    Console.Write("Re-enter Score: ");
                                    GetInputNumberGrade(inputNumberGrade);


                                }
                            }
                        }
                    }
                }

            }

Console Output Image

whats does if(variable ) means in c language?

I m currently preparing for gate , I have come across a question

#include<stdio.h>
main()
{
static int var=6;
printf("%d\t",var--);
if(var)
main();
}

output is 6 5 4 3 2 1

i wanna know why it terminated after 1??