將數(shù)據(jù)標(biāo)準(zhǔn)化或中心化
#標(biāo)準(zhǔn)化,減去均值再除以均方根,scale設(shè)為FALSE的時(shí)候是中心化,也就不除均方根
scmean <- scale(allmean[,2:17], center = TRUE, scale = TRUE)
求第2列的方差、平均值
sd(data[,2])
mean(data[,2])
簡(jiǎn)單分類(lèi)統(tǒng)計(jì)
引入plyr包
library(plyr)
按pic列和audios列分類(lèi)統(tǒng)計(jì)
count(data1, c(data1$pic,data1$audios))
按pic列分類(lèi),對(duì)reposts_count列求和,計(jì)算帶有不同圖片數(shù)的轉(zhuǎn)發(fā)次數(shù)和
a <- aggregate(data$reposts_count, data[13], sum) #data[13]為pic_num列
求帶1、2、3等不同圖片數(shù)的微博的平均reposts_count數(shù)
ave_count <- (a$x)/(count(data$pic_num)$freq)
將得到的新列添加至原有表中,并繪圖
a <- cbind(a$pic_num,round(ave_count,0)) #round保留0個(gè)小數(shù)
a <- data.frame(a) #如果要plot,則要先轉(zhuǎn)換成數(shù)據(jù)框
plot(a$pic_num,a$ave_reposts_count)
利用aggregate函數(shù)根據(jù)某列值分組,對(duì)多列求平均
根據(jù)第5列值分組,對(duì)5至11列應(yīng)用foo函數(shù),foo函數(shù)的作用是求平均值并保留小數(shù)點(diǎn)后2位
foo <- function(x){a<- mean(x);a<-round(a,2);return(a)}
part2 <-aggregate(c[5:11], by=list(sample=c[,5]), foo)
利用apply函數(shù)進(jìn)行數(shù)據(jù)初步分類(lèi)統(tǒng)計(jì)并繪制頻數(shù)分布直方圖
i = c(4,5,6,9,12,13,14,15,16,17,18,19) #i存儲(chǔ)需要處理的列數(shù)
apply(data[,i],2,mean) #對(duì)第i列以列的方式求平均數(shù)
apply(data[,i],2,summary)
par(mfrow=c(2,3)) #把畫(huà)布分為兩行三列,mfrow表示以行優(yōu)先填充
a <- i[1:6];b <- i[7:15]
names(data[2]) #獲取第二列的索引名
for(i in a) {hist(sort(data[,i]), col='lightblue',main=paste('The distribution of ',names(data[i])),ylab="count",xlab=names(data[i]),labels=TRUE,xlim=c(0,200000),ylim=c(0,3000));+
plot(density(data[,i]),main='',xlab='',ylab='',xaxt='n',yaxt='n')} #循環(huán)繪制hist密度分布圖
apply和lapply常遇錯(cuò)誤
#apply常發(fā)生dim(X)的值必需是正數(shù),
dimnames(x)[[1]] <- letters[1:8]
#lapply常用于數(shù)組
foo <- function(x){if(x!=0){round(log(x),0)}else{x=x}} #不加else的內(nèi)容,對(duì)數(shù)組lapply時(shí),x=0時(shí)經(jīng)過(guò)此函數(shù)x將轉(zhuǎn)換成null
topic <- unlist(lapply(data$topic,foo))