简体   繁体   English

如何从字符串转换为R中的数值

[英]How to convert from string to numeric value in R

i'm looking to graph the heights of a group of people in R 我正在寻找在R中一群人的身高的图表

B/ca height like 5-11 comes in as a string, I was wondering if there were any tips on how to convert to a number so it could be graphed. B / ca高度(例如5-11)以字符串形式出现,我想知道是否有任何技巧可以转换为数字,以便将其绘制出来。

I am assuming your data is a factor. 我假设您的数据是一个因素。 If this is correct you can edit all the levels to numeric values then convert the factor to a numeric vector. 如果正确,则可以将所有级别编辑为数值,然后将因子转换为数值向量。

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

Reminder that this works if your R read your data as a factor 提醒您,如果您的R将您的数据作为要素读取,则此方法有效

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

它也可以与基本R函数一起使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM