[SOLVED] create a function find the value in lists through getting the index value as vector in r


I am still new to R and need your help.

I have data in the form of an array, and I want to create a function that applies to a dataframe, to get 3 values from each row and use them as indices to get values from the list .

The function should take three values to identify the value in the array

select_value <- function(A, B, C) {
  result <-array_main[A, B, C]
  return (result)

and the array is

vector1 <- c(10, 20, 30, 40, 50, 60, 70, 80, 90)
vector2 <- c(100, 200, 300, 400, 500, 600, 700, 800, 900)
vector3 <- c(2, 4, 6, 8, 10, 12, 14, 16, 18)
array_main <- array(c(vector1, vector2, vector3), dim = c(3, 3, 3))

df <- data.frame (C1 = c(1, 2, 3), C2 = c(2, 1, 3), C3 = c(3, 2, 1))

So the function should take for example the first row from df [row values are (1,2,3)] and use that as indices for array_main to get array_main[1,2,3] and return the value 8, then the second row from df which is (2, 1, 2), so use that as indices for array_main to get array_main[2, 1, 2] and return the value 200, finally, the third row which is (3,3,1), so use that as indices for array_main to get array_main[3,3,1] and return the value 90 .

How can I get the values stored in the (result) variable as a vector?

Thank you so much for your help


You don’t really need the select_value function at all. You can do the entire thing like this:

#> [1]   8 200  90

Learning points

A couple of other points to note are than your function select_value is longer than it needs to be. Writing:

select_value <- function(A, B, C) {
  result <-array_main[A, B, C]
  return (result)

Is the same as writing

select_value <- function(A, B, C) {
  array_main[A, B, C]

The second point to note is that it isn’t a great idea to write a function that relies on data from outside the function which isn’t being passed in as an argument. A better way to write such a function would be:

select_value <- function(data, A, B, C) {
  data[A, B, C]

However, when we do that, we realise that select_value is essentially the same function as the square bracket itself. The above function is almost identical to defining select_value as:

select_value <- `[`

Perhaps more useful would be defining your function like this:

select_values <- function(data_array, index_df) {

Which, in your case, would produce:

select_values(array_main, df)
#> [1]   8 200  90

Answered By – Allan Cameron

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *