如何利用R语言计数
答案:1 悬赏:0 手机版
解决时间 2021-03-03 22:08
- 提问者网友:沦陷
- 2021-03-03 01:32
如何利用R语言计数
最佳答案
- 五星知识达人网友:污到你湿
- 2021-03-03 02:20
其基本思想就是把百分数按照字符处理,首先将“%”与数字分离,然后再将数除以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) )
> testnewdata1
v1 v2
1 0.78 0.43
2 0.65 0.56
3 0.32 0.23
> library(stringr)
> testnewdata2<-data.frame(lapply(testdata, function(x) as.numeric(str_extract(x,'[0-9.]+'))/100) )
> testnewdata2
v1 v2
1 0.78 0.43
2 0.65 0.56
3 0.32 0.23
替换百分号的思想还可以用下面的代码实现
> testnewdata3<-data.frame(lapply(testdata, function(x) as.numeric(gsub("\\%", "", x))/100))
> testnewdata3
v1 v2
1 0.78 0.43
2 0.65 0.56
3 0.32 0.23
> 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) )
> testnewdata1
v1 v2
1 0.78 0.43
2 0.65 0.56
3 0.32 0.23
> library(stringr)
> testnewdata2<-data.frame(lapply(testdata, function(x) as.numeric(str_extract(x,'[0-9.]+'))/100) )
> testnewdata2
v1 v2
1 0.78 0.43
2 0.65 0.56
3 0.32 0.23
替换百分号的思想还可以用下面的代码实现
> testnewdata3<-data.frame(lapply(testdata, function(x) as.numeric(gsub("\\%", "", x))/100))
> testnewdata3
v1 v2
1 0.78 0.43
2 0.65 0.56
3 0.32 0.23
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯