R using $ to reference a specific column

Hi R Community

I have a simple question, do I always have to type df$l1 to get the first column in the dateframe df ? I noticed that in some R-scripts they only write l1 and then R recognizes it as the column in df automatically.

image

Hi,

if you look to colnames(cbind(l1,l2)) you will see that the column names are l1 and l2. as.data.frame just takes the column names as names for the variables.

Note that l1and df$l1 as well as l2 and df$l2 are different objects:

l1 <- list("A", "G", "D")
l2 <- list(1,2,4)
df <- as.data.frame(cbind(l1, l2))
l2[[3]] <- 8  # now l2 and df$l2 are different
l2
df$l2
#iris is a built in data.frame that every R user would have

iris$Sepal.Length

Sepal.Length
#Error: object 'Sepal.Length' not found

#attach and detach to start and stop behaviour
attach(iris)

Sepal.Length

detach(iris)

Sepal.Length


#attach within curly brackets
with(iris,
     {
       Sepal.Length
      })

I would very rarely use such techniques but they have their occasional benefits.

Hi nirgrahamuk,
Say that im using iris$Sepal.Lenght and are tired of writing iris$Sepal.Lenght every time is there a ways to only write Sepal.Lenght and use the column without having to reference the dataframe? does it make sense?

Best Jakob

my code is an example of exactly what you said.

but of course, you at least have to mention iris once or it will be mysterious the computer where Sepal.Length is coming from ... my example is fairly complete and transparent. Do you have a specific question about it ?

nirgrahamuk, your right - just thought there was another solution without the attach

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.