apply函数
A=matrix(sample(1:20,16),4,4)
A
sample(1:20,5)
head(A)
apply(A, 2, sum)#对列求和
apply(A, 1, sum)#对行求和
apply(A,1,function(x){(x-min(x))/(max(x)-(min(x)))})#在行上对各数据进行归一化处理
apply(A,1,function(x){ifelse(is.na(x),0,1)})#在行上执行函数,na值等于0,非na值等于1
## Compute row and column sums for a matrix:
x <- cbind(x1 = 3,x3=runif(8,0,9),x2 = c(4:1, 2:5))
x
dimnames(x)[[1]] <- letters[1:8]#给矩阵加上行的名称
x
apply(x, 1, sum)
apply(x, 1, sum, trim = .2)#tirm为0.2时,计算总和加0.2
apply(x, 1, sum, trim = .5)#tirm为0.5时,计算总和加0.5
apply(x, 2, mean)
apply(x, 2, mean, trim = .2)
apply(x, 2, mean, trim = .5)
col.sums <- apply(x, 2, sum)
col.sums
row.sums <- apply(x, 1, sum)
row.sums
#cbind组合列,rbind组合行,对矩阵,求行列汇总值
rbind(cbind(x, Rtot = row.sums), Ctot = c(col.sums, sum(col.sums)))
stopifnot(apply(x, 2, is.vector))
diff函数
diff函数代码
## 示例1
chafen=sample(c(1:16),10)
chafen
diff(chafen,lag=2)#第三个数减第一个数,第四个数减第二个数,以此类推
diff(chafen)
diff(chafen,differences = 2)#做两次差分运算
##示例2
chafen1=1:10
chafen1
diff(chafen1)
diff(chafen1,lag=2)
diff(chafen1,differences = 2)
length(diff(chafen1))
diff函数运行结果
diff函数示例1运行结果
diff函数示例2运行结果
cast函数对数据整理
cast函数代码
test=data.frame(id=c("wang","li","zhang","liu"),zhuanye=c("林学","森林经理",
"林学","森林保护"),renshu=c(1,0,1,1))
test
library(reshape)
test1=cast(test,id~zhuanye,value ="renshu")
class(test1)
mode(test1)
test1
cast函数结果
cast函数结果
paste函数的运用
paste函数代码
paste('oc',sample(1:4,25,replace = T),sep = "")
paste('oc',sample(1:4,25,replace = T),sep = "",collapse="")#所有的元素连接成一起变为字符串
paste0('oc',sample(1:4,25,replace = T))#paste0函数默认前后字符直接连接
paste('oc',sample(1:4,25,replace = T))
paste('oc',c(2:5),sep="555")
paste(1:12)
paste0(1:12)
(nth <- paste0(1:12, c("st", "nd", "rd", rep("th", 9))))
paste(month.abb, "is the", nth, "month of the year.")
?paste
paste函数运行结果
Paste函数运行结果
网友评论