Information about variables

Problem

You want to find information about variables.

Solution

Here are some sample variables to work with in the examples below:

  1. x <- 6
  2. n <- 1:4
  3. let <- LETTERS[1:4]
  4. df <- data.frame(n, let)

Information about existence

  1. # List currently defined variables
  2. ls()
  3. #> [1] "df" "filename" "let" "n" "old_dir" "x"
  4. # Check if a variable named "x" exists
  5. exists("x")
  6. #> [1] TRUE
  7. # Check if "y" exists
  8. exists("y")
  9. #> [1] FALSE
  10. # Delete variable x
  11. rm(x)
  12. x
  13. #> Error in eval(expr, envir, enclos): object 'x' not found

Information about size/structure

  1. # Get information about structure
  2. str(n)
  3. #> int [1:4] 1 2 3 4
  4. str(df)
  5. #> 'data.frame': 4 obs. of 2 variables:
  6. #> $ n : int 1 2 3 4
  7. #> $ let: Factor w/ 4 levels "A","B","C","D": 1 2 3 4
  8. # Get the length of a vector
  9. length(n)
  10. #> [1] 4
  11. # Length probably doesn't give us what we want here:
  12. length(df)
  13. #> [1] 2
  14. # Number of rows
  15. nrow(df)
  16. #> [1] 4
  17. # Number of columns
  18. ncol(df)
  19. #> [1] 2
  20. # Get rows and columns
  21. dim(df)
  22. #> [1] 4 2