What is the difference between ls() command and objects() command in R?

R ProgrammingServer Side ProgrammingProgramming

They are actually no difference between the two commands as they give the same result that is the number of objects in the current workspace. If we have five different type of objects say a data frame, a matrix, a list, a data.table object, and a vector then both the commands will give the names of these objects.

Example

Consider the below objects −

Live Demo

> x1<-factor(sample(LETTERS[1:4],20,replace=TRUE))
> x2<-sample(LETTERS[1:4],20,replace=TRUE)
> df1<-data.frame(x1,x2)
> df1

Output

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

Example

Live Demo

> y1<-rnorm(20)
> y2<-rnorm(20)
> df2<-data.frame(y1,y2)
> df2

Output

y1 y2
1 0.65071307 1.02378223
2 -0.44122486 -0.87234919
3 1.04794035 1.04320326
4 0.01344608 -1.46007611
5 -0.34406863 1.61176666
6 0.62468548 -0.17394132
7 1.82751243 -0.13258166
8 -0.41707184 -0.09495451
9 1.16060850 -0.14671270
10 0.64134066 -0.78741462
11 1.24223245 1.14711590
12 -1.40133979 -0.63125311
13 -0.20832436 -0.18808274
14 -0.44245563 -0.40374874
15 1.00301606 0.95478376
16 1.04774024 -0.69940470
17 0.32013637 0.37317010
18 1.23054882 1.13829073
19 -0.28731032 0.60972393
20 1.28277393 1.45851332

Example

Live Demo

> z1<-rpois(20,5)
> z2<-rpois(20,5)
> df3<-data.frame(z1,z2)
> df3

Output

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

Example

> List<-list(x1,y1,z1)
> List

Output

[[1]]
[1] A D C A B B D D B B D A C C C B B A C D
Levels: A B C D

[[2]]
[1] 0.65071307 -0.44122486 1.04794035 0.01344608 -0.34406863 0.62468548
[7] 1.82751243 -0.41707184 1.16060850 0.64134066 1.24223245 -1.40133979
[13] -0.20832436 -0.44245563 1.00301606 1.04774024 0.32013637 1.23054882
[19] -0.28731032 1.28277393

[[3]]
[1] 4 10 7 1 9 2 4 4 3 0 2 5 4 3 4 5 3 9 6 9

Example

> ls()

Output

[1] "df1" "df2" "df3" "List" "x1" "x2" "y1" "y2" "z1" "z2"

Example

> objects()

Output

[1] "df1" "df2" "df3" "List" "x1" "x2" "y1" "y2" "z1" "z2"
raja
Published on 04-Jan-2021 06:34:49
Advertisements