1

So I have data looking like this.

I am trying to multiply a row given a specific Year and Name. I want to multiply the row by a value given it satisfies a given name and year requirement. For example Year = 2006, and Name = ABG Sundal Collier Holding. I find it hard to manipulate a row versus column that is easy to do changes in with dplyr package.

Any help would be greatly appreciated.

Edit: I'm not trying to make a new variable (or row), only multiplying the existing row with a value.

Kevin Cazelles
  • 1,255
  • 9
  • 20
  • in `data.table` the syntax is: `dt[ rowfilter, column := new_value]`. – Wimpel Mar 04 '20 at 13:21
  • 2
    Are you looking for `ifelse`? Like `df %>% mutate(new_var = ifelse(Year == 2006 & Name == "ABG Sundal Collier Holding", 2 * old_value, old_value))` – Allan Cameron Mar 04 '20 at 13:29
  • Thank you! I think ifelse is what im looking for. But i have problems applying it on my data. I'm not trying to make a new row, just replacing the values in the existing row with the new values – Snorre Hansen Mar 04 '20 at 13:50
  • 1
    Please include (some) data (`dput(mydata)` is best) and show the code you have tried so far – Richard Telford Mar 04 '20 at 13:54
  • Does this answer your question? [Can dplyr package be used for conditional mutating?](https://stackoverflow.com/questions/24459752/can-dplyr-package-be-used-for-conditional-mutating) – qdread Mar 04 '20 at 14:01

1 Answers1

0

You can conditionally replace the existing values in a row by using case_when or if_else:

library(tidyverse)

df <- data.frame(Name = rep("ABG Sundal Collier Holding", 3), Year = c(2004, 2005, 2006), SomeValue = c(5, 10, 15))

df <- df %>%
  mutate(SomeValue = case_when(Name == "ABG Sundal Collier Holding" & Year == 2006 ~ SomeValue * 10, 
        TRUE ~ SomeValue))

df <- df %>%
  mutate(SomeValue = if_else(Name == "ABG Sundal Collier Holding" & Year == 2006, SomeValue * 10, SomeValue))
Caitlin
  • 505
  • 2
  • 14