paste0 not printing the message inside else statement - r

I don't get any error but I was expecting that when I type an integer that is not 1,2,3,4 the code should enter in else statement and print what is in paste0 function. What is wrong?
escolha <- as.integer(readline(prompt="Enter your choice: "))
if(escolha == 1){
print("Cool you choose addition!")
} else if (escolha == 2) {
print("Cool, you choose subtraction!")
} else if (escolha == 3) {
print("Cool, you choose multiplication!")
} else if (escolha == 4){
print("Cool, you choose division!")
} else{
paste0("It's not possible to use ", escolha," as input.")
escolha<- as.integer(readline(prompt="Choose a valid number (1 a 4): "))
}
num1 <- as.double(readline(prompt="What is the first number? "))
num2 <- as.double(readline(prompt="What is the second number? "))
resultado <- switch (escolha, (num1+num2), (num1-num2), (num1*num2), (num1/num2))
cat("The result is: ", resultado)

paste0() (and paste()) assemble a string and return it. You still need to print the result to the screen with print() or cat(), like this:
cat(paste0("It's not possible to use ", escolha," as input.\n"))
(added the \n at the end, so the readline() prompt that follows will be on a separate line)

Related

In the R console, how do I delete one previous line?

I know how to delete everything in the console: cat('\014')
But there is a progress bar in 'R'. Somehow, it is possible to delete only one line, and not everything at all?
Example using backspace:
showMe <- function() {
txt <- ' Hello Wonderful World! '
n <- nchar(txt)
for ( i in 1:100 ) {
cat(txt)
flush.console()
Sys.sleep(0.15)
for ( j in 1:n ) { cat('\b') }
aChr <- substr(txt, 1, 1)
txt <- paste0( substr(txt, 2, n), aChr )
}
cat(' Goodbye Cruel World! \n' )
}
showMe()

Progress bar with non-changing line above (in R)

I would like to give a little informative message about where I am in the for-loop.
So I have this snippet of code:
for (i in 1:20) {
dashes = paste0(replicate(20, "-"), collapse = "")
cat("This should be above and not change")
cat(paste0("\r", i, " ", dashes))
Sys.sleep(0.3)
}
However, the output in the console looks like this:
9 --------------------This should be above and not change
While the number updates in place (which is the behavior I wanted), the "This should...", should be placed above and not move at all. I tried a couple of things but did not really succeed in doing so.
Not a very good question...
This simple if does the trick.
for (i in 1:20) {
dashes = paste0(replicate(20, "-"), collapse = "")
if (i == 1) {
cat("This should be above and not change\n")
}
cat(paste0("\r", i, " ", dashes))
Sys.sleep(0.3)
}

How to evaluate without unnecessary parentheses in Julia?

I have a case struct which holds an expression with the type of SymbolicUtils.Term{Bool}. Also I have defined rules from SymbolicUtils library which takes these cases as input and simplifies them. In order to simplify these cases the form should be like: (i == j) & (i == 3) & (j == 3) & (i == 3) & (j == 3) without unnecessary parentheses. For example it's not good to have this one: ((i == j) & ((i == 3) & (j == 3))) & ((i == 3) & (j == 3))
In order to solve this, I thought I can convert the expression with extra parentheses to string then I can process this string to get the desired form. I did this actually:
function reduce_parentheses(case::Case)
main_exp_string = ""
exp_to_str = repr(case.condition) #Convert case's condition into a string.
condition_list = split(exp_to_str, "&") #Split cases to subcases into a list.
for i in 1:length(condition_list) # Iterate cases list one by one.
stripped = lstrip(condition_list[i], [' ']) #Remove the whitespace at the beginning of the expression.
stripped = rstrip(stripped, [' ']) #Remove the whitespace at the end of the expression.
stripped = lstrip(stripped, ['(']) #Add opening parentheses at the beginning of the expression.
stripped = rstrip(stripped, [')']) #Add closing parentheses at the end of the expression.
#Get the desired form.
if i != 1
main_exp_string = main_exp_string * ' ' * '(' *stripped * ')'
elseif i == 1
main_exp_string = main_exp_string * '(' *stripped * ')'
end
if i != length(condition_list)
main_exp_string = main_exp_string * ' ' * '&'
end
end
println(main_exp_string)
exp = (Meta.parse(main_exp_string)) #Convert string back to an expression.
println(typeof(eval(exp))) #Convert expression back to SymbolicUtils.Term{Bool} type.
end
I can get the string in the desired form but when I try to turn it back into an expression I'm getting unnecessary parentheses with the different form because it's evaluating left to right I think.
Example:
The case with unnecessary parentheses: ((i == j) & ((i == 3) & (j == 3))) & ((i == 3) & (j == 3))
The processed string(desired form): (i == j) & (i == 3) & (j == 3) & (i == 3) & (j == 3)
Evaluated case: ((((i == j) & (i == 3)) & (j == 3)) & (i == 3)) & (j == 3)
How can I solve this? Maybe instead of converting it into a string can I do it in a smarter way?

Control file based attribute population : Unix shell

I have a control file header.cntrl. it has details of header. Example below...
cat header.cntrl
id, name, age, location, phone number
Now I am getting files from different sources,
Source 1 is sending input.dat file in the following format
cat input.dat
id, name, age, location, status, phone number
1,Abc, 34,India, active, 9999999999
Source 2 is sending data in the following format
cat input_2.dat
id, age, name, qualification, status, phone number, location
2,24,xyz, L L B, Active, 88888-88888, India
So different sources are sending files in different formats. We would need to convert those input files to header.cntrl file format.
I was trying this using awk code, but for each source, I'll need to write an awk code. Can we do it with a single script which can be used for any new future source as well?
This reformat_data script can reformat the two "non-standard" input formats and any future source formats. The key idea is to use Perl hashes to store the appropriate headings and only print those that are needed as specified in the header.cntrl file.
cat $* | perl -ne '
BEGIN {
#std_header = ("id","name","age","location","phone number");
print join(",", #std_header), ",\n";
chomp($firstline=<>);
$firstline =~ s/,\s+/,/g;
#inputfile_header=split(/,/, $firstline);
%hash=();
}
chomp;
#row = split(/,/);
$i=0;
for $cell (#row) {
$cell =~ s/\s+//;
$header=$inputfile_header[$i];
$hash{$header} = $row[$i];
$i++;
}
foreach $cell (#std_header) {
print "$hash{$cell},";
}
print "\n";
'
Here are the results of running the reformat_data script using the two sample input files:
cat input.dat
id, name, age, location, status, phone number
1,Abc, 34,India, active, 9999999999
reformat_data input.dat
id,name,age,location,phone number,
1,Abc,34,India,9999999999,
cat input_2.dat
id, age, name, qualification, status, phone number, location
2,24,xyz, L L B, Active, 88888-88888, India
reformat_data input_2.dat
id,name,age,location,phone number,
2,xyz,24,India,88888-88888,
In this particular case you can check the number of fields in lines (provided that all lines of a file have the same number of fields) (awk code):
{
n = split($0, a, "[ \t]*,[ \t]*");
if (n < 7) {
print a[1] ", " a[2] ", " a[3] ", " a[4] ", " a[6];
}
else {
print a[1] ", " a[3] ", " a[2] ", " a[7] ", " a[6];
}
}
A more sophisticated solution is to use the first line as key identifier and take remaining fields "by name":
{
n = split($0, a, "[ \t]*,[ \t]*");
if (FNR == 1) {
for (i = 1; i <= n; ++i) {
lbl[a[i]] = i;
}
}
print a[lbl["id"]] ", " a[lbl["name"]] ", " a[lbl["age"]] ", " a[lbl["location"]] ", " a[lbl["phone number"]];
}

R storing variable value in alist

I am trying to use a function to modify another function default settings through formals but my problem is that when I check my function defaults afterwards then nothing has changed. My code (minus unrelated stuff) is:
ScouringSettings <- function(min.MAF=NULL, eq.thresh=NULL){
if (is.null(min.MAF) && is.null(eq.thresh)){
maf <- paste0("Minimum MAF criterion is: ", formals(GeneScour)$min.maf)
eq <- paste0("ChiĀ² HW equilibrium threshold: ", formals(GeneScour)$min.eq)
cat(paste(maf, eq, sep="\n"))
} else if (is.null(eq.thresh)) {
formals(GeneScour) <- alist(gene=, min.maf = min.MAF, min.eq = formals(GeneScour)$min.eq)
} else if (is.null()){
formals(GeneScour) <- alist(gene=, min.maf = formals(GeneScour)$min.maf, min.eq = eq.thresh)
} else {
formals(GeneScour) <- alist(gene=, min.maf = min.maf, min.eq = eq.thresh)
}
}
I thought that maybe it was because of a problem of scope or something so I tried printing out the defaults while still being in my first function and it printed :
$gene
$min.maf
min.MAF
$min.eq
formals(GeneScour)$min.eq
And even when I forcefully type
formals(GeneScour) <- alist(gene=, min.maf = 2, min.eq = formals(GeneScour)$min.eq)
The modification is not carried over outside of the ScouringSettings.
I am a bit lost, how could I manage that ?

Resources