R语言提取数字的个位数

Python012

R语言提取数字的个位数,第1张

library(stringr)

q=74894

str_extract(q,'[0-9]{1}')

#?str_extract for more details

其基本思想就是把百分数按照字符处理,首先将“%”与数字分离,然后再将数除以100,就可以化成小数了。下面两种方法的区别一个是将%替换成空格,一个是提取除百分号的数字。>testdata<-data.frame(v1=c("78%", "65%", "32%"), v2=c("43%", "56%", "23%"))>testnewdata1<-data.frame(lapply(testdata, function(x) as.numeric(sub("%", "", x))/100) )>testnewdata1v1 v21 0.78 0.432 0.65 0.563 0.32 0.23>library(stringr)>testnewdata2<-data.frame(lapply(testdata, function(x) as.numeric(str_extract(x,'[0-9.]+'))/100) )>testnewdata2v1 v21 0.78 0.432 0.65 0.563 0.32 0.23 替换百分号的思想还可以用下面的代码实现>testnewdata3<-data.frame(lapply(testdata, function(x) as.numeric(gsub("\\%", "", x))/100))>testnewdata3v1 v21 0.78 0.432 0.65 0.563 0.32 0.23