Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python equivalent of get() in R (= use string to retrieve value of symbol)

Tags:

python

r

In R, the get(s) function retrieves the value of the symbol whose name is stored in the character variable (vector) s, e.g.

X <- 10
r <- "XVI"
s <- substr(r,1,1) ## "X"
get(s)             ## 10

takes the first symbol of the Roman numeral r and translates it to its integer equivalent.

Despite spending a while poking through R-Python dictionaries and Googling various combinations of "metaprogramming", "programming on the language", "symbol", "string", etc., I haven't come up with anything. (I am a very experienced R user and a novice Python user.)

(I know the example above is a (very!) poor way to approach the problem. I'm interested in the general answer to this question, not specifically in converting Roman numerals to integers ...)

like image 599
Ben Bolker Avatar asked Jan 30 '15 22:01

Ben Bolker


People also ask

Which function is equivalent to R in Python?

The pandas package for Python also has a function called apply, which is equivalent to its R counterpart; the following code illustrates how to use it.

How do I find the value of a variable in Python?

Use the type() Function to Check Variable Type in Python To check the type of a variable, you can use the type() function, which takes the variable as an input. Inside this function, you have to pass either the variable name or the value itself. And it will return the variable data type.

What is Percent R in Python?

%r shows the representation if the raw data of the variable.


1 Answers

You can use locals:

s = 1
locals()['s']

EDIT:

Actually, get in R is more versatile - get('as.list') will give you back as.list. For class members, in Python, we can use getattr (here), and for built-in things like len, getattr(__builtins__, 'len') works.

like image 102
zw324 Avatar answered Oct 03 '22 18:10

zw324