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
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.
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.
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.