How to Print the Structure of an R Object to the Console

How to print the structure of an R object to the console

The function is dput (or dump).

In R, how can I print the name of an object reliably from a custom print function?

The autoprinting documentation says it is handled by print.c.

This function looks like this.

static void PrintObjectS3(SEXP s, R_PrintData *data)
{
/*
Bind value to a variable in a local environment, similar to
a local({ x <- <value>; print(x) }) call. This avoids
problems in previous approaches with value duplication and
evaluating the value, which might be a call object.
*/
SEXP xsym = install("x");
SEXP mask = PROTECT(NewEnvironment(R_NilValue, R_NilValue, data->env));
defineVar(xsym, s, mask);

/* Forward user-supplied arguments to print() */
SEXP fun = PROTECT(findFun(install("print"), R_BaseNamespace));
SEXP args = PROTECT(cons(xsym, data->callArgs));
SEXP call = PROTECT(lcons(fun, args));

eval(call, mask);

defineVar(xsym, R_NilValue, mask); /* To eliminate reference to s */
UNPROTECT(4); /* mask, fun, args, call */
}

Note that it says

similar to a local({ x <- <value>; print(x) })

So autoprinting does not directly call print(myInstance). It does things with the symbol x so I think getting the variable name in the way you want is not possible.

The difference can be seen by looking at the traceback.

print.myobj <- function(x, ...) {
stop()
}

print(myInstance)
#> (Traceback)
#> 3. stop()
#> 2. print.myobj(myInstance)
#> 1. print(myInstance)

myInstance
#> (Traceback)
#> 3. stop()
#> 2. print.myobj(x)
#> 1. (function (x, ...)
#> UseMethod("print"))(x)

How to print struct variables in console?

To print the name of the fields in a struct:

fmt.Printf("%+v\n", yourProject)

From the fmt package:

when printing structs, the plus flag (%+v) adds field names

That supposes you have an instance of Project (in 'yourProject')

The article JSON and Go will give more details on how to retrieve the values from a JSON struct.


This Go by example page provides another technique:

type Response2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}

res2D := &Response2{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))

That would print:

{"page":1,"fruits":["apple","peach","pear"]}

If you don't have any instance, then you need to use reflection to display the name of the field of a given struct, as in this example.

type T struct {
A int
B string
}

t := T{23, "skidoo"}
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()

for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Printf("%d: %s %s = %v\n", i,
typeOfT.Field(i).Name, f.Type(), f.Interface())
}

What is printed when you call an object in R?

Neither lm nor print are part of the S4 system, so "SetMethod" is the wrong syntax. If instead you use the S3 syntax:

print.lm <- function(x) print(x$coef)

It does as you say (e.g. fit <- lm(cars$dist ~ cars$speed) yields the same results when calling print(fit) and just fit).

Is there a way to view a list

I use str to see the structure of any object, especially complex list's

Rstudio shows you the structure by clicking at the blue arrow in the data-window:

Sample Image

How to custom print/show variables (with custom class) in my R package

Here is a small explanation. Adding to the amazing answer posted by @nya:

First, you are dealing with S3 classes. With these classes, we can have one method manipulating the objects differently depending on the class the object belongs to.

Below is a simple class and how it operates:

  1. Class contains numbers,
  2. The class values to be printed like 1k, 2k, 100k, 1M,
  3. The values can be manipulated numerically.

-- Lets call the class my_numbers

Now we will define the class constructor:

 my_numbers = function(x) structure(x, class = c('my_numbers', 'numeric'))

Note that we added the class 'numeric'. ie the class my_numbers INHERITS from numeric class

We can create an object of the said class as follows:

b <- my_numbers(c(100, 2000, 23455, 24567654, 2345323))
b
[1] 100 2000 23455 24567654 2345323
attr(,"class")
[1] "my_numbers" "numeric"

Nothing special has happened. Only an attribute of class has been added to the vector. You can easily remove/strip off the attribute by calling c(b)

c(b)
[1] 100 2000 23455 24567654 2345323

vector b is just a normal vector of numbers.

Note that the class attribute could have been added by any of the following (any many more ways):

 class(b) <- c('my_numbers', 'numeric')
attr(b, 'class') <- c('my_numbers', 'numeric')
attributes(b) <- list(class = c('my_numbers', 'numeric'))

Where is the magic?

I will write a simple function with recursion. Don't worry about the function implementation. We will just use it as an example.

my_numbers_print = function(x, ..., digs=2,  d = 1,  L =   c('', 'K', 'M', 'B', 'T')){
ifelse(abs(x) >= 1000, Recall(x/1000, d = d + 1),
sprintf(paste0('%.',digs,'f%s'), x, L[d]))
}

my_numbers_print(b)
[1] "100.00" "2.00K" "23.45K" "24.57M" "2.35M"

There is no magic still. Thats the normal function called on b.

Instead of calling the function my_numbers_print we could write another function with the name print.my_numbers ie method.class_name (Note I added the parameter quote = FALSE

print.my_numbers = function(x, ..., quote = FALSE){
print(my_numbers_print(x), quote = quote)
}

b
[1] 100.00 2.00K 23.45K 24.57M 2.35M

Now b has been printed nicely. We can still do math on b

 b^2
[1] 10.00K 4.00M 550.14M 603.57T 5.50T

Can we add b to a dataframe?

data.frame(b)
b
1 100
2 2000
3 23455
4 24567654
5 2345323

b reverts back to numeric instead of maintaining its class. That is because we need to change another function. ie the formats function.

Ideally, the correct way to do this is to create a format function and then the print function. (Becoming too long)



Summary : Everything Put Together

# Create a my_numbers class definition function
my_numbers = function(x) structure(x, class = c('my_numbers', 'numeric'))

# format the numbers
format.my_numbers = function(x,...,digs =1, d = 1, L = c('', 'K', 'M', 'B', 'T')){
ifelse(abs(x) >= 1000, Recall(x/1000, d = d + 1),
sprintf(paste0('%.',digs,'f%s'), x, L[d]))
}

#printing the numbers
print.my_numbers = function(x, ...) print(format(x), quote = FALSE)

# ensure class is maintained after extraction to allow for sort/order etc
'[.my_numbers' = function(x, ..., drop = FALSE) my_numbers(NextMethod('['))

b <- my_numbers(c(2000, 100, 20, 23455, 24567654, 2345323))

data.frame(x = sort(-b) / 2)

x
1 -12.3M
2 -1.2M
3 -11.7K
4 -1.0K
5 -50.0
6 -10.0

How can I display a JavaScript object?

If you want to print the object for debugging purposes, use the code:

var obj = {
prop1: 'prop1Value',
prop2: 'prop2Value',
child: {
childProp1: 'childProp1Value',
},
}
console.log(obj)

will display:

screenshot console chrome

Note: you must only log the object. For example, this won't work:

console.log('My object : ' + obj)

Note ': You can also use a comma in the log method, then the first line of the output will be the string and after that, the object will be rendered:

console.log('My object: ', obj);

How to fully dump / print variable to console in the Dart language?

There is no built in function that generates such an output.

print(variable) prints variable.toString() and Instance of 'FooBarObject' is the default implementation. You can override it in custom classes and print something different.

You can use reflection (https://www.dartlang.org/articles/libraries/reflection-with-mirrors) to build a function yourself that investigates all kinds of properties of an instance and prints it the way you want.
There is almost no limitation of what you can do and for debugging purposes it's definitely a fine option.

For production web application it should be avoided because it limits tree-shaking seriously and will cause the build output size to increase notable.
Flutter (mobile) doesn't support reflection at all.

You can also use one of the JSON serialization packages, that make it easy to add serialization to custom classes and then print the serialized value.
For example

  • https://pub.dartlang.org/packages/dson

I think there are others, but I don't know about (dis)advantages, because I usually roll my own using https://pub.dartlang.org/packages/source_gen

R Function - Print When Not Assigned

Assuming that you still want your function to return the 'x+1' value, you could just wrap it in the invisible function:

fun <- function(x) {
print(x+1)
invisible(x+1)
}

> fun(3)
[1] 4

> a = fun(3)
[1] 4

> a
[1] 4

This will only print it out once, while still retaining the 'x+1' value.

R function that accepts an object and returns the code necessary to generate that object in the R interpreter

I think you are looking for dput.

For example, for 1st 5 rows of iris, you could do

dput(iris[1:5,])

#structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5), Sepal.Width = c(3.5,
#3, 3.2, 3.1, 3.6), Petal.Length = c(1.4, 1.4, 1.3, 1.5, 1.4),
# Petal.Width = c(0.2, 0.2, 0.2, 0.2, 0.2), Species = structure(c(1L,
# 1L, 1L, 1L, 1L), .Label = c("setosa", "versicolor", "virginica"
# ), class = "factor")), .Names = c("Sepal.Length", "Sepal.Width",
#"Petal.Length", "Petal.Width", "Species"), row.names = c(NA,
#5L), class = "data.frame")

and now you could use the same code to recreate the object again.

Another example,

x <- c(3, 4, 1, 2)
dput(x)
#c(3, 4, 1, 2)


Related Topics



Leave a reply



Submit