Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Map array of strings to an array of integers

Suppose I have a column in a data frame as colors say c("Red", "Blue", "Blue", "Orange"). I would like to get it as c(1,2,2,3).

Red as 1
Blue as 2
Orange as 3

Is there a simpler way of doing this other than the obvious if/else or switch functions?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Set up a named vector, describing the link between colour and integers (i.e. specifically how the strings map to the integers):

colors=c(1,2,3)
names(colors)=c("Red", "Blue", "Orange")

Now use the named vector to generate a list of numbers associated with the colours in your data frame:

>colors[c("Red","Blue","Blue","Orange")]
   Red   Blue   Blue Orange 
     1      2      2      3 

UPDATE to address questions below. Here's an example of what I think you're trying to do.

dataframe=data.frame(Gender=c("F","F","M","F","F","M"))
strings=sort(unique(dataframe$Gender))
colors=1:length(strings)
names(colors)=strings
dataframe$Colours=colors[dataframe$Gender]

Can have a look at the result:

> dataframe
  Gender Colours
1      F      1
2      F      1
3      M      2
4      F      1
5      F      1
6      M      2

Note that this example assumes that you have no specific mapping between Gender and Colours in mind. If this is really the case, then it might be simpler to just follow the comment from @alexis_laz instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...