Home > database >  Role of square brackets in R
Role of square brackets in R

Time:12-15

I got this code from elsewhere and I wondering if someone can explain what the square brackets are doing.

     matrix1[i,] <- df[[1]][] 

I am using this to assign values to a matrix and it works but I am not sure what exactly it's doing. What does the initial set of [[]] mean followed by another []?

Thank you in advance, Drashti

CodePudding user response:

This might help you understand a bit. You can copy and paste this code and see the differences between different ways of indexing using [] and $. The only thing I can't answer for you is the second empty set of square brackets, from my understanding that does nothing, unless a value is within those brackets.

#Retreives the first column as a data frame
mtcars[1]

#Retrieves the first column values only (three different methods of doing the same thing)
mtcars[,1]
mtcars[[1]]
mtcars$mpg

#Retrieves the first row as a data frame
mtcars[1,]

#I can use a second set of brackets to get the 4th value within the first column
mtcars[[1]][4]
mtcars$mpg[4]

CodePudding user response:

The general function of [ is that of subsetting, which is well documented both in help (as suggested in comments), and in this piece. The rest of of my answer is heavily based on that source.

In fact, there are operators for subsetting in R; [[,[, and $. The [ and $ are useful for returning the index and named position, respectfully, for example the first three elements of vector a = 1:10 may be subsetted with a[c(1,2,3)]. You can also negatively subset to remove elements, as a[-1] will remove the first index.

The $ operator is different in that it only takes element names as input, e.g. if your df was a dataframe with a column values, df$values would subset that column. You can achieve the same [, but only with a quoted name such as df["values"].

To answer more specifically, what does df[[1]][] do? First, the [[-operator will return the 1st element from df, and the following empty [-operator will pull everything from that output.

  •  Tags:  
  • r
  • Related