# What is the difference between $and @ in R? If we have a data frame defined as df that contains column x, y, and z then extraction of these columns from df can be done by using df$x, df$y, and df$z. On the other hand, if we have an S4 object defined as Data_S4 that contains column x, y, and z then the extraction of these columns can be done by using Data_S4@x, Data_S4@y, and Data_S4@z.

Example of a data frame:

## Example

Live Demo

> x1<-rpois(20,4)
> x2<-rpois(20,2)
> df<-data.frame(x1,x2)
> df

## Output

 x1 x2
1 4 2
2 7 0
3 10 2
4 3 1
5 7 1
6 2 2
7 3 4
8 4 2
9 7 1
10 2 2
11 1 1
12 6 2
13 1 2
14 1 4
15 1 0
16 4 4
17 5 1
18 5 1
19 6 2
20 3 1

## Output

[1] 2 0 2 1 1 2 4 2 1 2 1 2 2 4 0 4 1 1 2 1

Example of an S4 object:

## Example1

> setClass("data1",representation(x1="numeric",x2="numeric"))
> data1<-new("data1",x1=rnorm(20),x2=rexp(20,1.12))
> data1

## Output

An object of class "data1"
Slot "x1":
[1] -0.586187627 0.853689097 -0.602612795 -2.194235741 -1.318522292
[6] -0.984882420 0.273584140 0.364691611 1.025472248 1.198547297
[11] -0.709282551 -0.001441127 -0.201348012 1.296811172 1.520093861
[16] 2.071031215 0.472877022 0.616211695 0.642165615 -0.122773000

Slot "x2":
[1] 0.38902289 0.20631450 0.02105516 0.24891420 2.37347874 0.43704064
[7] 0.79887672 1.95711822 0.69214407 1.17875759 0.10490338 0.69417206
[13] 0.60324447 0.03573967 0.27204874 1.63015638 1.94575940 2.97829841
[19] 0.22643380 2.06821215

Extracting x1 and x2:

## Example

> data1@x1

## Output

[1] -0.586187627 0.853689097 -0.602612795 -2.194235741 -1.318522292
[6] -0.984882420 0.273584140 0.364691611 1.025472248 1.198547297
[11] -0.709282551 -0.001441127 -0.201348012 1.296811172 1.520093861
[16] 2.071031215 0.472877022 0.616211695 0.642165615 -0.122773000

## Example

> data1@x2

## Output

[1] 0.38902289 0.20631450 0.02105516 0.24891420 2.37347874 0.43704064
[7] 0.79887672 1.95711822 0.69214407 1.17875759 0.10490338 0.69417206
[13] 0.60324447 0.03573967 0.27204874 1.63015638 1.94575940 2.97829841
[19] 0.22643380 2.06821215

Updated on: 21-Nov-2020

243 Views