Reputation: 151
I have a data look's like this
df
df = data.frame(
id = c(1,1,1,1,1,2,2,2),
value = c('a','b','c','d','e','a','b','c'))
------------
id value
------------
1 a
------------
1 b
------------
1 c
------------
1 d
------------
1 e
------------
2 a
------------
2 b
------------
2 c
------------
now I want to add a new column based on the value that should look like this
---------------------------
id value from to
---------------------------
1 a a e
---------------------------
1 b a e
---------------------------
1 c a e
---------------------------
1 d a e
---------------------------
1 e a e
---------------------------
2 a a c
---------------------------
2 b a c
---------------------------
2 c a c
---------------------------
I don't know if the answer is already available if it already available please provide me the link
Upvotes: 0
Views: 50
Reputation: 51582
You can use ave
, along with head
(for first) and tail
(for last) i.e.
df$from <- with(df, ave(value, id, FUN = function(i)head(i, 1)))
#and
df$to <- with(df, ave(value, id, FUN = function(i)tail(i, 1)))
Using data.table
library(data.table)
setDT(df)[, c('from', 'to') := list(data.table::first(value), data.table::last(value)), by = id][]
Upvotes: 3
Reputation: 1411
Another solution using dplyr
:
library(dplyr)
df %>%
group_by(id) %>%
mutate(from = first(value), to = last(value))
id value from to
1 a a e
1 b a e
1 c a e
1 d a e
1 e a e
2 a a c
2 b a c
2 c a c
Upvotes: 2