R - Grouping observations based on a code list
I have a dataset where each observation has an integer variable "code" which I would like to convert to a class variable. Here is a simple example to illustrate what I am trying to do.
code.list <- data.frame(code = 1:10,
class = c("Class 1", "Class 2", "Class 3", "Class 4", "Class 5",
"Class 6", "Class 7", "Class 8", "Class 9", "Class 10"))
set.seed(1)
data <- data.frame(code = rbinom(100000, 10, 0.5))
> head(code.list, 4)
code class
1 1 Class 1
2 2 Class 2
3 3 Class 3
4 4 Class 4
> head(data, 4)
code
1 4
2 4
3 5
4 7
I want to add a class variable to data
so that the class for each observation corresponds to the corresponding "code" variable in code.list
. Is there a way to do this without using a for loop and repeating each observation?
source to share
If I understood your problem, then I think you really want to search / concatenate a table, if then you can use data.table
to solve this problem:
library(data.table)
data <- data.table(data)
code.list <- data.table(code.list)
data[code.list, class := i.class, on="code"]
Thanks Frank, I was guided that there is a better way to do things in the data.table, I updated the same.
data[code.list, class := i.class,on="code"]
> data
code class
#1: 5 Class 5
#2: 5 Class 5
#3: 6 Class 6
#4: 6 Class 6
#5: 5 Class 5
---
#99996: 5 Class 5
#99997: 6 Class 6
#99998: 8 Class 8
#99999: 6 Class 6
#100000: 5 Class 5
>
source to share