Adam_G
Adam_G

Reputation: 7879

R: Create Variable and Display Value in Single Command

Is there a way to both create a variable and output its value in a single command? In other words, concatenating both lines below into a single command?

x <- mean(1:7)
x

Upvotes: 0

Views: 95

Answers (1)

Pierre L
Pierre L

Reputation: 28441

Wrap the command in parantheses.

(x <- mean(1:7))

Knowing this you can do a few cool R tricks like creating an object and using it in the same expression. The development team does this all over the R source code. This is a double nest from apply:

if (length(dn.call) && !is.null(n1 <- names(dn <- dn.call[1])) && 
        nzchar(n1) && length(ans.names) == length(dn[[1]])) 

Be careful with these newfound powers, your co-workers will never be able to read your code again :)

Upvotes: 1

Related Questions