How to call a value in a r data frame based on another value in the same row

Hey All,
I need to know how to call a cell based on the date in the row.

library(reprex)
library(tidyverse)

eqs <- data.frame(
  energy = c(48.99, 13.34, 2.67, 6.25, 4.93, 2.71, 4.73, 16.38),
  period = c(seq(from = as.Date("2019-07-01"), to = as.Date("2019-07-08"), by = 'day')),
  stringsAsFactors = FALSE)

eqs1 <- eqs %>% 
  mutate(Eight_Day_ROI = '?' / '?')
#> Error in "?"/"?": non-numeric argument to binary operator

I think we need more information. Can you explain how the value of Eight_Day_ROI is determined? Do you want to compare each energy value with the energy value from 8 days previous?

1 Like

The Eight_Day_ROI doesn't really matter I just want to know how I would return the energy value for a specific date.

But yea i want to compare the energy values from those two different days by calling the energy value by date.

To get a single value out of a data frame, you can use square brackets. The variable Value will have the value 48.99.

Value <- eqs[eqs$period == as.Date("2019-07-01"), "energy"]

You may not want to use the mutate() function as that makes a whole new column and if you pass it a single value, the whole column will have that value.

library(dplyr)

eqs <- data.frame(
  energy = c(48.99, 13.34, 2.67, 6.25, 4.93, 2.71, 4.73, 16.38),
  period = c(seq(from = as.Date("2019-07-01"), to = as.Date("2019-07-08"), by = 'day')),
  stringsAsFactors = FALSE)
Value <- eqs[eqs$period == as.Date("2019-07-01"), "energy"]
eqs2 <- eqs %>% mutate(ROI = Value)                                        
eqs2
#>   energy     period   ROI
#> 1  48.99 2019-07-01 48.99
#> 2  13.34 2019-07-02 48.99
#> 3   2.67 2019-07-03 48.99
#> 4   6.25 2019-07-04 48.99
#> 5   4.93 2019-07-05 48.99
#> 6   2.71 2019-07-06 48.99
#> 7   4.73 2019-07-07 48.99
#> 8  16.38 2019-07-08 48.99

Created on 2019-09-09 by the reprex package (v0.2.1)

1 Like

I'm probably just going to have a new data frame with different ROI's

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