Reputation: 407
I have following dataframe,
Here I want to add a column 'Constant Vol', where if the 'Year' column is 2006 all the values for 'Constant Vol' should be that od 2006 'Vol'. The result should be like following dataframe.
Upvotes: 0
Views: 50
Reputation: 887881
We can use
library(dplyr)
df %>%
group_by(Seg) %>%
mutate(Constnt_Vol = Vol[match(2006, Year)])
df <- data.frame(Seg = rep(c("Agri", "Auto"), each =4),
Year =2006:2009, Vol = c(23, 29, 16, 31, 12, 34, 45, 32))
Upvotes: 0
Reputation: 389265
Using dplyr
, we can group_by
Seg
and get the corresponding Vol
where Year = 2006
library(dplyr)
df %>%
group_by(Seg) %>%
mutate(Constnt_Vol = Vol[Year == 2006])
# Seg Year Vol Constnt_Vol
# <fct> <int> <dbl> <dbl>
#1 Agri 2006 23 23
#2 Agri 2007 29 23
#3 Agri 2008 16 23
#4 Agri 2009 31 23
#5 Auto 2006 12 12
#6 Auto 2007 34 12
#7 Auto 2008 45 12
#8 Auto 2009 32 12
and in data.table
that would be
library(data.table)
setDT(df)[, Constnt_Vol := Vol[Year == 2006], Seg]
This is assuming you have only one row with Year = 2006
in each Seg
, if there are multiple we can use which.max
to get the first one. (Vol[which.max(Year == 2006)]
).
data
df <- data.frame(Seg = rep(c("Agri", "Auto"), each =4),
Year =2006:2009, Vol = c(23, 29, 16, 31, 12, 34, 45, 32))
Upvotes: 1