先看一下R能干什么
df <- mtcars
?mtcars
names(df)
head(df)
nrow(df)
summary(df)
hist(df$hp)
plot(df$hp,df$qsec)
cor(df$hp,df$qsec)
cor(df$cyl,df$qsec)
df$hpPerCyl <- df$hp/df$cyl
df[order(df$hpPerCyl),]
head(df[order(df$hpPerCyl),])
基础内容
如何给变量赋值
#either
x <- 1
#or
x = 1
注意不要忘了空白号,x<-1会被翻译成x <- 1而不是x < -1
R的基本原子类型(atomic types)
x <- TRUE #class(x) is "logical"
x <- 1L #class(x) is "integer"
x <- 1.5 #class(x) is "numeric"
x <- 1.5 + o.4i #class(x) is "complex"
x <- "Text" #class(x) is "character"
R中不含有标量(scalars),标量在这里被表示为长度为1的向量。
TRUE和FALSE可以简单的用T,F来代替
Strings即可以用双括号也可以用单括号阔起来
如何调用函数
ls #is a function object
ls() #is the object returned by calling the function
如何寻求帮助
#open help:
?ls
#search help for the specific topic:
??correlation
#other functions to analyze things
str(x)
summary(x)
class(x)
attributes(x)
R的控制流
#if:
if(STATEMENT)
STATEMENT
else
STATEMENT
#for loop:
for(name in vector)
STATEMENT
#repeat
repeat
STATEMENT #until 'break' is called
有趣的地方是:if结构可以被当成statement使用(只有if结构可以):
y <- if(x > 0) "y" else "no"
另外STATEMENT也可以被用{}包围起来的一组statement代替,这些语句可以全部扔在一行,也可以分成多行写
if({x <- mean(1:5); y <- mean(1:4); x<y}){
cat("evaluating the 'true' block \n")
"y"
}else {
cat("evaluating the 'false' block \n")
"n"
}
向量(Vectors)
如何生成向量
x <- c(1,2,3) #c for "c"Kombine
x <- seq(1,3) #to create a sequence, with possibility to
x <- seq(1,3,by=0.5) #-define step size
x <- se