2

So I know that double brackets return the element only while single brackets return a list with that element inside. But how does this matter functionally when making functions or for loops?

Say I have a set of X and Y values, and want to find the best slope and y intersect for them. I have a list of x and y values ( stored in data1) and a list of yintersect and slope values (stored in parameters).

I want to see which set of y-intersect and slope values comes closest to the actual Y values. So first I will make a function which outputs the y value GIVEN a set of yintersect and slope values from the parameters list. This function is showed below titled modelling_function

parameters <- list(yintersect = c(1:10), slope = c(5:14))

data1 <- list(x = sample(100, 10), y = sample(200:10))

modelling_function <- function(parameters, data1) { 
parameters[[1]]+ parameters[[2]] * data1$x}

So two questions...

  1. What is the difference between using single and double brackets here?
  2. Why when I run this function do I only get 10 values? I would expect to get 10 * 10 = 100 values, because for each x value, there are 10 combinations of slope and intersect to be used.

I know im missing something here, I think related to what exactly is being done to each vector/list. I hope the brackets and knowing what is being done to each subsetted list will help me figure that out.

Peter
  • 11,500
  • 5
  • 21
  • 31
Kevin Lee
  • 321
  • 2
  • 8
  • 3
    Did you read https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el ? – Ronak Shah Jun 22 '20 at 04:18
  • Try it: with one bracket, `Error in parameters[2] * data1$x : non-numeric argument to binary operator`. This is because `parameters[2]` is a list, not a numeric vector. – Rui Barradas Jun 22 '20 at 04:36
  • for your data1 and parameters you will get vector of length 10 beacause parameters$yintersect and parameters$slope have length 10 and data1$x has length 10 – det Jun 22 '20 at 06:06

1 Answers1

1

[[ is used to subset only one element from a vector and it peels off the outer structure if the vector is a list:

a <- list(1:3, c("a", "b", "c"), 100:107)
a[[1]]

[1] 1 2 3

Note that a[[1]] is not a list but an integer vector (you can imagine that you [draw from the] list by taking an element from [the corresponding] position in that list).

a[1]

[[1]]
[1] 1 2 3

Note that [ is keeping the structure, a[1] returns a subset of the vector -- in this case its a list with 1 element. With [ you can subset more than 1 element:

a[c(1,3)]

[[1]]
[1] 1 2 3

[[2]]
[1] 100 101 102 103 104 105 106 107

You can use [[ and [ on other vector types. But because there is no outer structure to peel off, they will return same value when subsetting 1 element of the vector.

x <- 1:10

x[[1]]
[1] 1

x[1]
[1] 1

x[c(1,3)]
[1] 1 3
det
  • 5,013
  • 1
  • 8
  • 16