Home > Blockchain >  How to access list elements in R?
How to access list elements in R?

Time:11-07

I have a list named as change_points composed of 6 rows with 1 or 2 elements in each. It looks like this: enter image description here

My question is, how can I access just 654 from 2nd row? Or any single value or any row.

I've search over SO, and I've only come up with sapply(change_points,`[`,c(1)) which shows me the first element of each row.

Any guidance please?

CodePudding user response:

There is no row attribute in a list. A list can have a length attribute which is 6 (based on the image). So, if we need to extract the value 654, which is the 2nd element of the vector which is the 2nd element of the list

change_points[[2]][2]

The change_points[[2]] extracts the 2nd list element as a vector and then use [2] to extract the 2nd element of the vector


When we specify the index as 1, it returns the first element only

sapply(change_points,`[`, 1)

Here, the sapply is looping over all the list elements and extracting the 1st element. If it should be the second element, change the 1 to 2. But, we only need the value of the second list element, so looping over all elements is not needed

  • Related