무회blog

R함수 basic002 : apply(),lapply(),sapply(),tapply() ,rep , matrix 사용법 본문

Python/R

R함수 basic002 : apply(),lapply(),sapply(),tapply() ,rep , matrix 사용법

최무회 2020. 6. 3. 18:42
# install.packages("installr")
# install.packages('RmecabKo') # C++ 기반으로 함,
# install.packages("ggplot2")
# install.packages("readxl")
# install.packages("dplyr")
# install.packages("rJava")

## testData is mpg

library(installr)
library(ggplot2)  # mpg
library(readxl)
library(dplyr)
library(rJava)

## tt: apply(),lapply(),sapply(),tapply() ,rep , matrix , apply
###########################################
## tt: apply(),lapply(),sapply(),tapply()   shiyongfa 
list(1:4,6:10)
mylist <- list(1:4,6:10,list(1:4,6:10))
mylist
mylist[[3]]
lapply(mylist[[3]], mean)  # pintjunzhi 

lapply(mylist[c(1,2,c(1,2))], mean)  # pintjunzhi 
unlist(lapply(mylist[c(1,2,c(1,2))], mean))  # pintjunzhi 
sapply(mylist[c(1,2,c(1,2))], mean)  # pintjunzhi 

wordlist <- c("the","is","a","the")
doc1freq <- c(3,4,2,4)
doc2freq <- rep(1,4)     # 1 chu sige
wordlist
doc1freq
doc2freq
length(doc1freq)
length(doc1freq)
length(doc2freq)
tapply(doc1freq, wordlist, length)
tapply(doc2freq, wordlist, length)
tapply(doc1freq, wordlist, sum)
tapply(doc2freq, wordlist, sum)

# "earth to earth; ashes to ashes; dust to dust"
sent1 <- c("earth","to","earth")
sent2 <- c("ashes","to","ashes")
sent3 <- c("dust","to","dust")
myfreq <- c(rep(1,length(sent1)),rep(1,length(sent2)),rep(1,length(sent3)))
myfreq
tapply(myfreq, c(sent1,sent2,sent3), sum)
###########################################
# rname =c("one","two","three")
# rname
# 
# cname = c("first","second")
# cname
# b <- matrix(1:6,nrow=3, dimnames = list(rname,cname))
# b
# 
# apply(b, 1, sum)  # rowSum
# apply(b, 2, sum)  # colSum
# apply(b, 2, max)  # colSum
# 
# x=array(1:24,c(2,3,4))  # hang, lie , ciyuan
# x
# 
# apply(x, 1, sum)  # hengjia 
# apply(x, 2, sum)  # shujia 
# apply(x, 3, sum)  # ciyuanjia 
###########################################



Comments