I have a df1:
ID Score
XF7 4
XF4 6
XF10 5
DE10 3
XF4 1
DE10 6
DE11 2
R3 8
PPR16 2
DE11 10
I would like to replace the ID's with a number that is unique to the ID. For example XF7 could be "1" while all of the XF4's would be "2".
ID Score NumID
XF7 4 1
XF4 6 2
XF10 5 3
DE10 3 4
XF4 1 2
DE10 6 4
DE11 2 5
R3 8 6
PPR16 2 7
DE11 10 5
CodePudding user response:
We may use match
df1$NumID <- with(df1, match(ID, unique(ID)))
-output
> df1
ID Score NumID
1 XF7 4 1
2 XF4 6 2
3 XF10 5 3
4 DE10 3 4
5 XF4 1 2
6 DE10 6 4
7 DE11 2 5
8 R3 8 6
9 PPR16 2 7
10 DE11 10 5
CodePudding user response:
Assuming your character IDs are unique, you could convert them to their ASCII encodings.
Define function for converting string to ASCII:
string_to_ASCII <- function(s) {
paste0(utf8ToInt(s))
}
Replace column of interest:
df1$ID <- lapply(df1$ID, string_to_ASCII)
CodePudding user response:
Another possible solution:
library(dplyr)
df %>%
group_by(ID) %>%
mutate(NumID = cur_group_id()) %>%
ungroup()
#> # A tibble: 10 × 3
#> ID Score NumID
#> <chr> <int> <int>
#> 1 XF7 4 7
#> 2 XF4 6 6
#> 3 XF10 5 5
#> 4 DE10 3 1
#> 5 XF4 1 6
#> 6 DE10 6 1
#> 7 DE11 2 2
#> 8 R3 8 4
#> 9 PPR16 2 3
#> 10 DE11 10 2