Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

r - Simplest way to replace a list of values in a data frame with a list of new values

Say we have a data frame with a factor (Group) that is a grouping variable for a list of IDs:

set.seed(123)
data <- data.frame(Group = factor(sample(5,10, replace = T)),
                   ID = c(1:10))

In this example, the ID's belong to one of 5 Groups, labeled 1:5. We simply want to replace 1:5 with A:E. In other words, if Group == 1, we want to change it to A, if Group == 2, we want to change it to B, and so on. What is the simplest way to achieve this?

question from:https://stackoverflow.com/questions/65948347/simplest-way-to-replace-a-list-of-values-in-a-data-frame-with-a-list-of-new-valu

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You may assign new labels= in a names list using factor once again.

data$Group1 <- factor(data$Group, labels=list("1"="A", "2"="B", "3"="C", "4"="D", "5"="E"))
## more succinct:
data$Group2 <- factor(data$Group, labels=setNames(list("A", "B", "C", "D", "E"), 1:5))
data
#    Group ID Group1 Group2 Group3
# 1      3  1      C      C      C
# 2      3  2      C      C      C
# 3      2  3      B      B      B
# 4      2  4      B      B      B
# 5      3  5      C      C      C
# 6      5  6      E      E      E
# 7      4  7      D      D      D
# 8      1  8      A      A      A
# 9      2  9      B      B      B
# 10     3 10      C      C      C

This for general, if indeed capital letters are wanted see @RonakShah's solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...