my_matrix<-matrix(nrow=2,ncol=2)
my_martix<-matrix(nrow=8,ncol=4)
#Itcreatesamatrixwith8rowsand4cloumns.
#Butinitiallytheyallareempty(NA).
#Theseareusedtoenterthedataintothematrix.
#Herec()functionisusedtoconcatenatethedata.
#Inthebelowexamplethedataisfilledbycolumnwise.
my_martix[,1]<-c(59,55,53.5,55,52.5,57.5,53,55)
my_martix[,2]<-c(22.3,19.7,20.8,20.3,20.8,21.5,20.6,21.5)
my_martix[,3]<-c(31.2,30.4,30.6,30.3,30.3,30.8,32.5,34)
my_martix[,4]<-c(9.5,13.8,14.8,15.2,15.5,15.6,15.6,15.7)
print(my_martix)
[,1][,2][,3][,4]
[1,]59.022.331.29.5
[2,]55.019.730.413.8
[3,]53.520.830.614.8
[4,]55.020.330.315.2
[5,]52.520.830.315.5
[6,]57.521.530.815.6
[7,]53.020.632.515.6
[8,]55.021.534.015.7
>df<-data.frame(id=letters[1:5],x=1:10,y=rnorm(10))
>df
>##idxy
>##1a1-1.37593
>##2b20.47094
>##3c3-0.16046
>##4d4-1.36914
>##5e50.39763
>x<-factor(c("yes","no","no","yes","yes"))
>x
[1]yesnonoyesyes
Levels:noyes
#table(x)willreturnafrequencytable.
if(condition){
#dosomething
}else{
#dosomethingelse
}
x<-1:15
if(sample(x,1)<=10){
print("xislessthan10")
}else{
print("xisgreaterthan10")
}
for(iin1:5){
print(i)
}
1
2
3
4
5
x<-c("apples","oranges","bananas","strawberries")
#Printsthelistitemswiththeindex.
for(iinx){
print(x[i])
}
for(iin1:4){
print(x[i])
}
for(iinseq(x)){
print(x[i])
}
#Inline
for(iin1:4)print(x[i])
[1]NA
[1]NA
[1]NA
[1]NA
[1]"apples"
[1]"oranges"
[1]"bananas"
[1]"strawberries"
[1]"apples"
[1]"oranges"
[1]"bananas"
[1]"strawberries"
[1]"apples"
[1]"oranges"
[1]"bananas"
[1]"strawberries"
while(condition){
statements
iteration
}
i<-1
while(i<5){
print(i)
i<-i+1
}
1
2
3
4
5
repeat{
condition
statements
break
}
x<-1
repeat{
print(x)
x=x+1
if(x==6){
break
}
}
[1]1
[1]2
[1]3
[1]4
[1]5
function_name<-function(arg_1,arg_2,...){
functionbody
}
my_function<-function(a){
for(iin1:a){
b<-i^3
print(b)
}
}
#Nowcallthefunctionsupplying6asanargument
my_function(6)
216
>install.packages("ggplot2")
library(ggplot2)
#Plotsmpgdataset'swithXaxis-displandYaxis-hwy
#Wecanalsospecifythecolorpalletebysendingthecolourargument.
ggplot(mpg,aes(displ,hwy,colour=class))+geom_point()
原文連結:https://towardsdatascience.com/r-lang-zero-to-hero-c59a9f66841c