问题描述
假设我在数据框中有一列,如颜色 c(红色,蓝色,蓝色,橙色)。我想把它作为 c(1,2,2,3)。
红色为1
蓝色为2
橙色为3
有没有比明显的if / else或switch函数更简单的方法?
设置描述颜色和整数之间的链接(即具体如何映射到整数): c(1,2,3)
名称(颜色)= c(红色,蓝色,橙色)
现在使用命名向量生成与数据框中颜色关联的数字列表:
>颜色[c(红,蓝,蓝,橙)]
红蓝蓝橙
1 2 2 3
更新以解决以下问题。这是我认为你想要做的一个例子。
dataframe = data.frame(Gender = c(F F),F,M))
strings = sort(unique(dataframe $ Gender))
colors = 1:length(strings)
名称(颜色)=字符串
数据框$颜色=颜色[数据框$性别]
可以看看结果:
>数据帧
性别颜色
1 F 1
2 F 1
3 M 2
4 F 1
5 F 1
6 M 2
请注意,此示例假定您在性别和颜色之间没有具体的映射。如果确实如此,那么只需按照@alexis_laz中的评论就可以更简单。
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?
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.
这篇关于将字符串数组映射到整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!