Get Type of All Variables

Get type of all variables

You need to use get to obtain the value rather than the character name of the object as returned by ls:

x <- 1L
typeof(ls())
[1] "character"
typeof(get(ls()))
[1] "integer"

Alternatively, for the problem as presented you might want to use eapply:

eapply(.GlobalEnv,typeof)
$x
[1] "integer"

$a
[1] "double"

$b
[1] "character"

$c
[1] "list"

Is there a way to get to all variables of a certain type in a class?

Your code "compiles" to this:

var MyClass = (function () {
function MyClass() {
}
return MyClass;
}());

with nothing in there as you can see... however if you initialize your properties it will result some like this:

source TS:

class MyClass {
myNum1: number = 0;
myNum2: number = 0;
myNum3: number = 0;
myString: string = "";
myBoolean: boolean = false;
}

result JS:

var MyClass = (function () {
function MyClass() {
this.myNum1 = 0;
this.myNum2 = 0;
this.myNum3 = 0;
this.myString = "";
this.myBoolean = false;
}
return MyClass;
}());

then you can check instance properties:

var instance = new MyClass();
Object.keys(instance) //["myNum1", "myNum2", "myNum3", "myString", "myBoolean"]
instance["myNum1"] // 0

with that in mind you can filter the properties that you need:

var numerics = Object.keys(instance).map(k => instance[k]).filter(v => v.constructor === Number)
console.log(numerics) //[0, 0, 0]

Determine the data types of a data frame's columns

Your best bet to start is to use ?str(). To explore some examples, let's make some data:

set.seed(3221)  # this makes the example exactly reproducible
my.data <- data.frame(y=rnorm(5),
x1=c(1:5),
x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
X3=letters[1:5])

@Wilmer E Henao H's solution is very streamlined:

sapply(my.data, class)
y x1 x2 X3
"numeric" "integer" "logical" "factor"

Using str() gets you that information plus extra goodies (such as the levels of your factors and the first few values of each variable):

str(my.data)
'data.frame': 5 obs. of 4 variables:
$ y : num 1.03 1.599 -0.818 0.872 -2.682
$ x1: int 1 2 3 4 5
$ x2: logi TRUE TRUE FALSE FALSE FALSE
$ X3: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5

@Gavin Simpson's approach is also streamlined, but provides slightly different information than class():

sapply(my.data, typeof)
y x1 x2 X3
"double" "integer" "logical" "integer"

For more information about class, typeof, and the middle child, mode, see this excellent SO thread: A comprehensive survey of the types of things in R. 'mode' and 'class' and 'typeof' are insufficient.

Get all variable names in a class

Field[] fields = YourClassName.class.getFields();

returns an array of all public variables of the class.

getFields() return the fields in the whole class-heirarcy. If you want to have the fields defined only in the class in question, and not its superclasses, use getDeclaredFields(), and filter the public ones with the following Modifier approach:

Modifier.isPublic(field.getModifiers());

The YourClassName.class literal actually represents an object of type java.lang.Class. Check its docs for more interesting reflection methods.

The Field class above is java.lang.reflect.Field. You may take a look at the whole java.lang.reflect package.

pandas how to check dtype for all columns in a dataframe?

The singular form dtype is used to check the data type for a single column. And the plural form dtypes is for data frame which returns data types for all columns. Essentially:

For a single column:

dataframe.column.dtype

For all columns:

dataframe.dtypes

Example:

import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})

df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')

df.dtypes
#A int64
#B bool
#C object
#dtype: object

find the type of all variables in scope python

You may be looking for locals, which returns a dict with locals vars name and their values:

for name, value in locals().items():
if isinstance(value, someclass):
do something

OK, I am editing this answer, because it is the closest of what I want:
I wanted to erase all numpy array. I find it annoying that numpy does not have "clear all" a la octave\matlab, and ipython's %reset is a bit too much ...

so, here it is:
In [24]: anp=np.r_[1:10]

 In [25]: np.who()
Name Shape Bytes Type
===========================================================

anp 9 36 int32

Upper bound on total bytes = 36

In [26]: for name, value in locals().items():
....: if isinstance(value, np.ndarray):
....: print name
....: print value
....: del globals()[name]
....:
anp
[1 2 3 4 5 6 7 8 9]

In [27]: np.who()

Upper bound on total bytes = 0

Thanks for everyone, for the will and the effort!

How to print all of the variables and their type inside a function

Are you looking for something like this:

# define these outside the scope of the function
x = 10
y = 20

def function():
a = 3;
b = 4;
c = float(b+a)
l = locals()
print(", ".join(["{var}: {type}".format(var=v, type=type(l[v])) for v in l]))

function()
#a: <type 'int'>, c: <type 'float'>, b: <type 'int'>

How to get all variables of a class in angular

I found what im was looking for. The solution is create a ItemController, thanks everyone!

export class Item {
item_id: number;
item_quantidade: number;
item_unidade_medida: number;
item_descricao: string;
item_codigo: string;
item_marca: string;
item_fornecedor: string;
item_unitario_compra: number;
item_unitario_venda: number;
item_parte_caminhao: string;
item_aplicacao: string;
item_usu_cadastro: string;
item_usu_data_cadastro: Date;
item_usu_alteracao: string;
item_usu_data_alteracao: Date;
item_status: string;
}

export class ItemController {
_item: Item;

constructor() {
this._item = new Item();
this.resetItem();
}

public get getItem(): Item {
return this._item;
}
public setItem(item: Item) {
this._item = item;
}

}

How to get a variable type in Typescript?

For :

abc:number|string;

Use the JavaScript operator typeof:

if (typeof abc === "number") {
// do something
}

TypeScript understands typeof /p>

This is called a typeguard.

More

For classes you would use instanceof e.g.

class Foo {}
class Bar {}

// Later
if (fooOrBar instanceof Foo){
// TypeScript now knows that `fooOrBar` is `Foo`
}

There are also other type guards e.g. in etc https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html



Related Topics



Leave a reply



Submit