'include list elements in column R
I would like to add the list elements into a column by group. A reproducible example below. Do you know how to achieve this?
library(data.table)
a <- c("A","A","A","A","B","B","C","C","C","D")
b <- seq(1,10)
dt <- data.table(a,b)
list <- c(15,10,9,120)
dt <- data.table(a,b, c(15,15,15,15,10,10,9,9,9,120))
View(dt)
Solution 1:[1]
One way would be using match -
library(data.table)
dt[, new := list[match(a, unique(a))]]
dt
# a b new
# 1: A 1 15
# 2: A 2 15
# 3: A 3 15
# 4: A 4 15
# 5: B 5 10
# 6: B 6 10
# 7: C 7 9
# 8: C 8 9
# 9: C 9 9
#10: D 10 120
Solution 2:[2]
Another way, using rep and rle:
library(data.table)
a <- c("A","A","A","A","B","B","C","C","C","D")
b <- seq(1,10)
dt <- data.table(a,b)
list <- c(15,10,9,120)
dt[, c := rep(list, rle(dt$a)$l)]
# a b c
# 1: A 1 15
# 2: A 2 15
# 3: A 3 15
# 4: A 4 15
# 5: B 5 10
# 6: B 6 10
# 7: C 7 9
# 8: C 8 9
# 9: C 9 9
#10: D 10 120
Solution 3:[3]
Maybe this one?
> dt[, new := list[.GRP],a][]
a b new
1: A 1 15
2: A 2 15
3: A 3 15
4: A 4 15
5: B 5 10
6: B 6 10
7: C 7 9
8: C 8 9
9: C 9 9
10: D 10 120
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ronak Shah |
| Solution 2 | |
| Solution 3 | ThomasIsCoding |
