Home > OS >  What is the difference between $ and [] in terms of the output in R ? when I extract data.frame
What is the difference between $ and [] in terms of the output in R ? when I extract data.frame

Time:02-21

I use package 'tidytuesdayR'

target<-tidytuesdayR::tt_load(2021,30)
df<-target$drought

df$map_date
df[,1]

What is the difference between df$map_date and df[,1] in terms of the output? What functions will you use to explain the differences between them?

CodePudding user response:

x$var is a shorthand for x[["var"]]

There are two main differences:

1. $ cannot be used with a character variable

Eg:

### All examples are from Hadley Wichams _Advanced R_ - see link at end of answer.
var <- "cyl"
# Doesn't work - mtcars$var translated to mtcars[["var"]]
mtcars$var
#> NULL

# Instead use [[
mtcars[[var]]
#>  [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

2. $ uses left-to-right partial matching

This makes it convenient for interactive use, but unpredictable. For this reason, many people use [[ rather than $ when writing function and scripts, and use $ for convenience whilst interacting directly with data.

Partial matching example:

x <- list(abc = 1)
x$a
#> [1] 1
x[["a"]]
#> NULL

Further reading

For more info on these operators, and a reasonably thorough look "under the hood" of the R engine, check out Hadley's Advanced R, which is available for free online. These examples are reproduced from his section on subsetting.

CodePudding user response:

$ is 1-dimension vector not including name of column [] is data.frame so including name of column

  •  Tags:  
  • r
  • Related