Assign custom factor values ββto each symbol group
I have one column of my dataframe that contains some symbols and a vector of factors. I would like to have a coefficient assigned to each group of values, so that the first group of characters gets the first coefficient, the second group gets the second, etc.
Col of data frame + vector of factors:
df$charac
:
charac
1 0
2 0
3 0
4 1
5 1
6 2
7 2
8 2
9 3
10 4
11 4
12 4
vec_factor
:
[1] 39 42 76 89 68
Levels: 39 42 68 76 89
Expected results:
charac factor
1 0 39
2 0 39
3 0 39
4 1 42
5 1 42
6 2 76
7 2 76
8 2 76
9 3 89
10 4 68
11 4 68
12 4 68
Data:
Vector of factors:
structure(c(1L, 2L, 4L, 5L, 3L), .Label = c("39", "42", "68",
"76", "89"), class = "factor")
col characters:
structure(list(test_vector = c("0", "0", "0", "1", "1", "2",
"2", "2", "3", "4", "4", "4")), .Names = "test_vector", row.names = c(NA,
-12L), class = "data.frame")
source to share
You can do it in R base:
df$factor<- as.factor(df$test_vector)
levels(df$factor) <- levels(vec_factor)
# test_vector factor
# 1 0 39
# 2 0 39
# 3 0 39
# 4 1 42
# 5 1 42
# 6 2 68
# 7 2 68
# 8 2 68
# 9 3 76
# 10 4 89
# 11 4 89
# 12 4 89
So, first create a type type column and then replace the levels with levels vec_factor
.
OR (thanks @alexis_laz for pointing this out)
df$factor <- factor(df$test_vector, labels = levels(vec_factor))
source to share
We can do it
df1$factor <- as.character(vec_factor)[as.integer(df1[[1]])+1]
df1$factor
#[1] "39" "39" "39" "42" "42" "76" "76" "76" "89" "68" "68" "68"
Or use match
df1$factor <- with(df1, vec_factor[match(test_vector, unique(test_vector))])
df1$factor
#[1] 39 39 39 42 42 76 76 76 89 68 68 68
#Levels: 39 42 68 76 89
NOTE. Both methods are inbase R
source to share