Fork me on GitHub

R

as.logical

1
2
3
myvector[as.logical (myvector<17)]  #subset data <17
myvector[as.logical ((myvector%%3==0) | (!(myvector%%2==0)))]
myvector[(myvector%%3==0)| (myvector%%2!=0)] #as.logical可以省略

as.character

-convert all the things to character

1
myvector[as.logical ((myvector%%3==0) | (!(myvector%%2==0)))]

table

-gives you list of all elements and counts them

sample

-gives you random numbers from a vector

1
2
set.seed(17)  ##使用这个可以随机输出固定的数据
sample(1:100,10)

rnorm

-gives you 10 random numbers from normal distribution with mean=0 and sd=1

1
2
rnorm(10, mean = 0, sd = 1)  
plot(density(rnorm(10, mean = 0, sd = 1)))

举个栗子:估计Pi值

1
2
3
4
5
6
7
set.seed(555) #所有人都能得到相同的结论
x <- runif(1000000,-1,1) #x <- runif (min=-1,max=1,n=10000)
y <- runif(1000000,-1,1)
res <- x^2 +y^2
mean <- mean (res <=1)
pi <- 4\*mean
pi

function

1
2
3
4
5
6
7
f <- function (a,b){
x = a+b
y = b/5
return (x\*y)
}
f(3,5)
result is 8

you can plot the chart directly

1
2
3
4
5
6
7
f <- function (x){
print (table (x))
plot (table(x))
a<- length(x)
return(a) #return(length(a))
}
f(c(1:20,5:10,1223,111))

sapply

1
2
3
4
5
6
7
x <- list(A=c(1,2,3,4,5),
B=c(1,3,5),
C=1)
proberi <- function(x){
sum(x[x>2])
}
sapply(x,proberi)

unique

unique (iris[,5]) #不重复的取出第五列所有的行

data frames

1
2
3
4
iris[10, "Petal.Length"] #第一个参数是row,第二个是列
iris[5, c("Petal.Length","Sepal.Width")] #5 row, petal.length 且 sepal.width line
iris[iris$Petal.Length>2, c(2,3)] #过滤petal.length 大于2的行,然后输出第2和3列
subset(iris, Petal.Length>2, 2,3)

以物种分开序列,然后输出每个物种的平均长度

1
2
3
4
5
s <- split(my.iris, my.iris$Species)
m <- function(x){
mean (x$Sepal.Length) #mean(my.iris[my.iris$Species=="versicolor", "Sepal.Width"])
}
sapply(s,m)

生成一个列表

1
2
3
4
ddf <- data.frame(
x = runif (100000, -1,1),
y = runif (100000, -1,1)
)

加头

colnames(ddf2) <- c("a","b", "c","d","e")

ggplot

facet_wrap #可以按照species把图片分开

ggplot(iris,aes(Sepal.Width,Petal.Length))+geom_point(aes(color=Species))+geom_smooth(method="lm")+facet_wrap(~Species)

facet_grid #可以分开横、纵两个坐标

1
2
ggplot(iris,aes(Sepal.Width,Petal.Length))+geom_point(aes(color=Species))+geom_smooth(method="lm") + facet_grid(Species~factor(iris$Sepal.Length>mean(iris$Sepal.Width))) 
ggplot(iris,aes(Sepal.Width,Petal.Length))+geom_point(aes(color=Species))+geom_smooth(method="lm") + facet_grid(Species~cut(iris$Sepal.Width,3))

theme_dark() #改变主题

ggthemes

ggsave

ggsave(file="mygraph.pdf", width=10, height=15)
or

1
2
3
pdf("mygraph.pdf", width=10,height=15)
ggplot……
dev.off()

plotly

https://images.plot.ly/plotly-documentation/images/plotly_js_cheat_sheet.pdf

1
2
3
4
5
6
library(plotly)
gg = ggplot(iris, aes(Sepal.Length, x=Species))+
geom_boxplot()
gg

ggplotly(gg)
------ END Thankyou ------