How do I use multiple variables in an IDL plot title? - idl-programming-language

In IDL I would like to create a title for my plot using variable names and their values computed during the program. For a single variable, TITLE = var_name.
How would I list two variable names and their values within the TITLE keyword?
Something like TITLE = "var1:" var1 "var2:" var2 doesn't work, and no combinations of quotes and commas seems to work.
Thank you.

The TITLE keyword expects a string. If you have several names and values you have to decide how to make them into a string. For example, you could do this with a structure in a simple manner:
IDL> s = { var1: 0., var2: 3. }
IDL> t = ''
IDL> for i = 0, n_tags(s) - 1L do $
IDL> t += string((tag_names(s))[i], s.(i), format='(A, ": ", F, " ")')
IDL> print, t
VAR1: 0.0000000 VAR2: 3.0000000
You can, of course, get as fancy with the format codes as you want.

Related

Alternative to making a dictionary from text document

I took word pairs from a text file and made a dictionary:
x = open('sustantivos.txt', 'r') ## opens file and assigns it to a variable
y = x.read() ## reads open file object and assigns it to variable y
y = str(y).lower().replace(":", "") ## turns open file object into a string, then makes it lower case and replaces ":" with whitespace
z = y.splitlines() # make a list with each element being a word pair string, then assign to variable z
bank = {}
for pair in z: #go through every word pair string
(key, value) = pair.split() #split the word pair string making a list with two elements, assign these to variable key and value
bank[key] = value #add key value pair
x.close()
For reference this is an excerpt from the text file:
Amour: amor
Anglais: inglés
Argent: dinero
Bateau: barco
My question is: Is there are more efficient or different approach that you would do differently? Also I was curious if my understanding that I include in the comments is correct. Thanks in advance.
Your inline notes are accurate except that line number 2 is where the opened file is read and its contents are turned into a string. Your use of str(y) in the third line is unnecessary and could simply be written as y.lower()...
Your parsing strategy is sound as long as you know that the file will always contain lines of key:value pairs on each and every line. However, There are a couple of recommendation I would make.
Use a with statement when opening files. this avoids errors that can occur if the file isn't closed properly
Don't read the whole file in at once.
dict.update will take an iterable of length 2 as an argument
Using those tips your code can be rewritten as:
bank = {}
with open('sustantivos.txt', 'r') as x:
for line in x:
key, value = line.strip().split(':')
bank[key] = value
# bank.update([line.strip().split(':')]) <- or this

R: Loop should return numeric element from string

I have a question how to write a loop in r which goes checks if a certain expression occurs in a string . So I want to check if the the expression “i-sty” occurs in my variable for each i between 1:200 and, if this is true, it should give the corresponding i.
For example if we have “4-sty” the loop should give me 4 and if there is no “i-sty” in the variable it should give me . for the observation.
I used
for (i in 1:200){
datafram$height <- ifelse(grepl("i-sty", dataframe$Description), i, ".")
}
But it did not work. I literally only receive points. Attached I show a picture of the string variable.
enter image description here
"i-sty" is just a string with the letter i in it. To you use a regex pattern with your variable i, you need to paste together a string, e.g., grepl(paste0(i, "-sty"), ...). I'd also recommend using NA rather than "." for the "else" result - that way the resulting height variable can be numeric.
for (i in 1:200){
dataframe$height <- ifelse(grepl("i-sty", dataframe$Description), i, ".")
}
The above works syntactically, but not logically. You also have a problem that you are overwriting height each time through the loop - when i is 2, you erase the results from when i is 1, when i is 3, you erase the results from when i is 2... I think a better approach would be to extract the match, which is easy using stringr (but also possible in base). As a benefit, with the right pattern we can skip the loop entirely:
library(stringr)
dataframe$height = str_match(string = dataframe$Description, pattern = "[0-9]+-sty")[, 2]
# might want to wrap in `as.numeric`
You use both datafram and dataframe. I've assumed dataframe is correct.

Specify the number of columns read_csv is applied to

Is it possible to pass column indices to read_csv?
I am passing many CSV files to read_csv with different header names so rather than specifying names I wish to use column indices.
Is this possible?
df.list <- lapply(myExcelCSV, read_csv, skip = headers2skip[i]-1)
Alternatively, you can use a compact string representation
where each character represents one column: c = character, i
= integer, n = number, d = double, l = logical, f = factor, D
= date, T = date time, t = time, ? = guess, or ‘_’/‘-’ to
skip the column.
If you know the total number of columns in the file you could do it like this:
my_read <- function(..., tot_cols, skip_cols=numeric(0)) {
csr <- rep("?",tot_cols)
csr[skip_cols] <- "_"
csr <- paste(csr,collapse="")
read_csv(...,col_types=csr)
}
If you don't know the total number of columns in advance you could add code to this function to read just the first line of the file and count the number of columns returned ...
FWIW the skip argument might not do what you think it does (it skips rows rather than selecting/deselecting columns): as I read ?readr::read_csv() there doesn't seem to be any convenient way to skip and/or include particular columns (by name or by index) except by some ad hoc mechanism such as suggested above; this might be worth a feature request/discussion on the readr issues list? (e.g. add cols_include and/or cols_exclude arguments that could be specified by name or position?)

bquote, parsing, expression to get multiple lines labels in ggplot with greek letters and variables as subscripts

Let's say I have
paste0("Year = ",index,"\nN = ",length((dfGBD %>% filter(year==index))[[vbl]]),
" Bandwidth = ",round(stats::bw.nrd(log((dfGBD %>% filter(year == index))[[vbl]])),2),
"\nSkewness:", round(e1071::skewness(log((dfGBD %>% filter(year==index))[[vbl]])), 2),
" Kurtosis:",round(e1071::kurtosis(log((dfGBD %>% filter(year==index))[[vbl]])),2),
"\nmu[",vbl,"] = ", round(mean((dfGBD %>% filter(year==index))[[vbl]]),2),
" sigma[",vbl,"] = ",round(sd((dfGBD %>% filter(year==index))[[vbl]]),2)
)
inside a sapply through index years. Further, vbl is a string with the name of a variable. The sapply produces a vector of labels for a factor variable.
Applying ggplot I obtain labels similar to the next:
Year = 2000
N = 195 Bandwidth = 0.09
Skewness: 0 Kurtosis: -0.56
mu[Mortality] = 7750.85 sigma[Mortality] = 1803.28
Till here, all ok. I have already written mu[vbl], sigma[vbl] thinking in parsing and subscript notation to get the greek letters with the name of the variable saved in vbl as subscript.
First I tried facet_wrap with option labeller = "label_parsed". I obtained an error which I only solved writting the string between backticks ``, but then \n has no effect. I tried many options using bquote and/or parse and/or expression and/or atop etc. in order to get this multiple lines result with the desired output I described above. But only get or one line or very ugly outputs or, mostly, errors, and I couldn't see yet the greek letters.
So what/how should I do?
PS: as answered in other stackoverflow's, \n does not work in this context, so a list with bquote's for each line is suggested. I tried it, but then I got an error that I think is due to incompatibility of number of elements of all the lists and number of labels of a factor (a label may not be a list?).
Thank you!

R - Plot: How to format in 10-base scientific notation and put it text, mtex, title etc functions?

I have numeric variable, say K=3.5e-5 (its values is calculated throughout my script). I want to write this value somewhere (title, as text in the plot, etc) in my plot as:
K_{root} = 3.5 10^{-5} cm /d
I have tried the functions bquote, substitute and no one worked.
Let's put the question in examples. I have tried the following:
1)
png("exp_1.png")
kroot = 3.5e-5
plot(1:10,1:10,
text(4,9,bquote(italic(K[root])~"="~.(kroot)~"cm/d")))
dev.off()
Try my favorite function, paste().
plot(1:10,1:10,
text(4,9,gsub("e",paste("K[root]=",format(k,scientific=TRUE),"cm/d",sep=" "),replacement=" 10^")))
You can replace the "e" here using the function gsub. I've edited my answer to include this.
The output:
> k=.0000035
> k
[1] 3.5e-06
> gsub("e",paste("K[root]=",format(k,scientific=TRUE),"} cm/d",sep=" "),replacement=" 10^{ ")
[1] "K[root]= 3.5 10^{ -06 } cm/d"
You can remove the extra spaces around { -06 } by using the function substr, if it's important, or simply leave out the curly brackets in the gsub statement.
I try to avoid using paste inside expressions. There is generally a cleaner way to approach this:
expon <- floor(log10(kroot)) # returns -5
mantis <- kroot*10^(-1*expon ) # returns 3.5
plot(1:10,1:10,
text(4,9,substitute( italic(K[root]) == mantis %.% pten* expon ~cm/d,
list(expon=expon, mantis=mantis, pten=" 10^")))

Resources