Sowmya S. Manian Sowmya S. Manian - 2 months ago 6
R Question

Why data frame column names different using = and <- in R

Can any body explain why the below two data frames

df1
and
df2
are differing in their column names

df1 <- data.frame(a = 1:5, b = 11:15)
df1
# a b
# 1 1 11
# 2 2 12
# 3 3 13
# 4 4 14
# 5 5 15

df2 <- data.frame(a <- 1:5, b <- 11:15)
df2
# a....1.5 b....11.15
# 1 1 11
# 2 2 12
# 3 3 13
# 4 4 14
# 5 5 15

Answer

The <- operator not only assigns objects but creates them in the parent environment unlike = operator

Renaming columns slightly:

df1 <- data.frame(a1 = 1:5, b1 = 11:15)



df1
#   a1  b1
# 1 1 11
# 2 2 12
# 3 3 13
# 4 4 14
# 5 5 15


#The objects are only created in the dataframee but not in environment  
# > exists(x = "a1")
#[1] FALSE
#> exists(x = "b1")
#[1] FALSE


#The objects are not only in created in the dataframe as well as in the environment

df2 <- data.frame(a2 <- 1:5, b2 <- 11:15)
df2
#   a2....1.5 b2....11.15
# 1        1         11
# 2        2         12
# 3        3         13
# 4        4         14
# 5        5         15

# > exists(x = "a2")
#[1] TRUE
#> exists(x = "b2")
#[1] TRUE
Comments