设矩阵为A
方法一:colSums(A)
方法二:apply(A,2,sum)
>x<-matrix(c(1,1,2,1,2,3,4,1),4,2)
>x
[,1] [,2]
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 1 1
>length(which((x[,1]==1)))
[1] 3
>length(which((x[,2]==1)))
[1] 1
#x[,1]==1判断是否为1,返回True或False
# which((x[,1]==1))返回为True的行号
#length(which((x[,1]==1)))返回为True的行数,即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