My first function

Hi there!
I've been trying to code my first function with no succes and i think that the solution might be in front of me.
This is a simplificcation of my data

Ticker metric1 metric2 metric3
HD 1 3 4
WMT 6 8 2
NVDA 1 2 3

I would like to make a list of every "Ticker" and thieir possible values, like this.

HD 1
WMT 6
NVDA 1
HD 3
HD 4
WMT 8
WMT 2
NVDA 2
NVDA 3

To do so, i created my first function but when i try to rbind the information i dont have dataframes, only a list of items and i can work with it.

metrica <- function(x) {
  x <- yahoo %>% select('Ticker','metric'=x+1)
}
n <- length(colnames(yahoo))-1
total <- rbind(lapply(1:n,metrica))

Why is it displayed as a list? There is something wrong with my code?

Thank you!

I am not exactly sure what the end result is you are trying to get to, so it is hard for to manipulate your data to get there.

Your function results is a tibble. When you called lapply, the tibbles were placed into a list objects. You then called rbind, which bound the lists together.

If all you want is to gather all the metric values into a single column, a gather should be sufficient. The following code will do the job. The last line will delete what were the column names, to make it more similar to your desired results.

yahoo %>%
  gather(-Ticker,
         key = "metric",
         value = "val") %>%
  select(-metric)

Created on 2020-05-30 by the reprex package (v0.3.0)

1 Like

I fully support using an existing function to do this if the outcome is all that matters. If the goal is to learn about function, then I suggest modifying the function as follows.

library(dplyr)

yahoo <- data.frame(Ticker = c("HD", "WMT", "NVDA"),
                    metric1 = c(1,6,1), metric2 = c(3,8,2), metric3 = c(4,2,3))
metrica <- function(x) {
  yahoo %>% select(1, Value = x + 1)
}
n <- length(colnames(yahoo))-1
total <- bind_rows(lapply(1:n,metrica))
total
#>   Ticker Value
#> 1     HD     1
#> 2    WMT     6
#> 3   NVDA     1
#> 4     HD     3
#> 5    WMT     8
#> 6   NVDA     2
#> 7     HD     4
#> 8    WMT     2
#> 9   NVDA     3

Created on 2020-05-30 by the reprex package (v0.3.0)
What you were trying to do inside the select() function by setting 'metric' = x + 1 will not work. It is easier to just use the numeric positions of the desired columns. I did use the select() function to rename the second selected column, so the data frames would all have the same column names and could be bound together.

2 Likes

Thank you! I did not know about gather function, and it was all that i needed. You saved me a lot of time!

Thank you!

Thank you, FJCC. I did not know about gather, so i will use that instead of my function.

I will have in mind your corrections, in order to be better in my next function.

Thank you for your time!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.