>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
上图是一个简单的例子,b为一矩阵,现在想统计第二列中数值等于1的元素个数,首先做一个逻辑判断,即b[,2]==1,得到一个由布尔变量true和false组成的向量。
此时只需要知道true的数量,由于对布尔变量求和,true转化为1,false转化为0,故对该向量求和即可得到true的数量,即b[,2]中等于1的数量。