如何用R语言将56个数字分8组

Python014

如何用R语言将56个数字分8组,第1张

其基本思想就是把百分数按照字符处理,首先将“%”与数字分离,然后再将数除以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

public class Test{

public static void main(String[] args){

new Test().random10()

}

public void random10(){

Random r = new Random()// 与Math.random()均可

HashSet<Integer>s = new HashSet<Integer>()

while(s.size() <10){

// int i = (int)(Math.random() * 100)

int i = r.nextInt(100)

//判断是否在set集里

if(!s.contains(i)){//这个判断可以不需要, 因为Set集, 不允许重复

s.add(i)

}

}

for(Integer i : s){

System.out.print(i + " ")

}

}

}