如何在R中将字符串转换为数字值

时间:2013-11-13 21:59:42

标签: string r graph ggplot2 numeric

我想要绘制R中一群人的高度

B / c像5-11这样的高度作为一个字符串出现,我想知道是否有关于如何转换为数字的任何提示,以便可以将其绘制成图形。

3 个答案:

答案 0 :(得分:0)

我假设您的数据是一个因素。如果这是正确的,您可以将所有级别编辑为数值,然后将因子转换为数字向量。

levels(data$heights)  #Levels of the factor
levels(data$heights)<-c(5*12+10,5*12+11,6*12,6*12+1) #Renaming factors in numerical make sure
##the numbers are in the same order as in your levels
data$heights<-as.numeric(levels(data$heights))[data$heights]  #Changing factor GPA to numeric vector GPA
data$heights

提醒您,如果您的R将数据读取为因子

,则此方法有效

答案 1 :(得分:0)

require(stringr) 
Split <- str_split(x, "-")
sapply(Split, function(x) x[1] + (x[2] / 11))

答案 2 :(得分:0)

它也适用于基本R函数:

sapply(strsplit(x, "-"), function(x) {x <- as.numeric(x); x[1] + x[2] / 12})