R Sprache

先看一下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 <- seq(1,3,len=10)    #-define numer of steps
x <- 1:3        #quick notation for integer sequences
x <- rep(0,10)  #repeat first "vector" 10 times
x <- numeric(10)#"numeric" vector of length 10
x[1] = 10
x[2] = 20
x[3] = 30

无论如何c()的结果都会被铺平所以试试这个吧:

x <- c(1,c(c(2,3),c(4,5,6)))

另外原子向量中是允许缺值的:

c(T,F,T,NA)
c(1:5,NA)
c("A",NA,"B","C",NA)

如果在一个Vector中混合不同类型的值会怎么样呢

因为vector中的值的类性应该一直保持一致,因此当上述情况发生时,R会强制改变类型。他们的优先顺序是:logical,integer,numeric,complex,character

#notice how the type changes when you remove elements from the end
x <- c(T,1L,1.0,1i,"text")
#notice that modifying elements can change the whole type
x <- rep(F,10)
x[6] = "text"

关于vector的一些重要函数

x <- runif(10)

length(x)
sum(x)

#statistics
mean(x)
median(x)
var(x)
sd(x)
quantile(x)

#range related
min(x)
max(x)
range(x)

#sorting related
sort(x)
rank(x)
order(x)

#vectorized functions
x + 1
x * 10
x < 0.5
(x < 0.2)|(x > 0.8)
sin(x)
exp(x)
round(x)

如果用不同长度的两个vector进行运算会怎么样

c(1,2,3,4) + c(1,2)
c(1,2,3,4) + c(1,2,3)
c(1,2,3,4) > 1

R采用的是循环的机制,但这也就要求长的vector的长度应该是短的vector的长度的整数倍

如何使用索引

x <- 1:10 * 10

#a positive index select an element
#a negative index omits an element
x[3]
x[-3]

#indices can again be vectors
x[c(1,3,5)]
x[3:5]
x[-c(1,3,5)]
x[-(3:5)]
#note:mixing positive and negative indices does not make sense

#indices can also be logical vectors
x[c(T,F,T,F,T,F,F,F,F,F)]
x[x == 10 | x == 30]

#indices can even be named
names(x) <- c("a","b","c","d","e","f","g","h","i","j")
x
x["c"]

矩阵和数组

R的vector其实就是其他语言中的array。他没有纬度的概念,只有长度。
R的array是特指多维的array。他有确定的纬度。但是本质上,他也是由vector实现的
R的matrix就是指一个二维的array

如何构建一个matrix

#generate without a vector
m <- matrix(nrow=2, ncol=3)
m[1,1] = 1
m[2,1] = 2
m[1,2] = 3
m[2,2] = 4
m[1,3] = 5
m[2,3] = 6

#generate from ONE vector
matrix(1:6, nrow=2, ncol=3)
matrix(1:6, nrow=2)
matrix(1:6, ncol=3)
matrix(1:6, byrow=TRUE, ncol=3)

#generate from multiple column/row vectors
rbind(c(1,3,5),c(2,4,6))
cbind(1:2,3:4,5:6)

因为matrix本质上就是一个拥有纬度的vector,因此也可以通过vector来构造matrix

m <- 1:12
dim(m) <- c(2,6)
dim(m) <- c(3,2,2)
c(is.vector(m),is.matrix(m),is.array(m))

matrix又是如何使用索引的呢

和vector一样

m[2,2]
m[1,1:3]
m[1,]
m[,2]

唯一不同的是现在要给元素起名的话,要加上纬度属性了

colnames(m) <- c("A","B","C")
rownames(m) <- c("o1","o2")
dimnames(m)

attibutes(m)

进行简单的线性运算

m <- cbind(1:2,3:4,5:6)

#multiply by vectors
m %*% c(1,2,4)
c(5,6) %*% m

第一个c三行一列,第二个c一行两列。真心不知道他在玩什么。以为他能自动转化吗,于是试了以下用c(1,2,3,4) %% m.结果却是出现错误,我还以为可以自动翻译成两行两列呢??然后又试了以下,5 %% m。结果还是错了

#multiply by matrices
m %*% matrix(runif(6),nrow=3)

#typical unary operators
m <- cbind(1:2,3:4)
t(m)        #transpose
diag(m)     #diagonal
solve(m)    #inverse
eigen(m)    #eigenvector/eigenvalues

#solving linear equations
solve(m,c(1,1)) #solve mx=c(1,1) for x

#misc matrix functions
dim(m)
nrow(m)
ncol(m)
rowSums(m)
colSums(m)
rowMeans(m)
colMeans(m)

其他数据类型

R语言中的list

#to construct a list
l <- list(name="Joe", unemployed=FALSE, salary=50000)

#naming the fields is optional 
l <- list("Joe",FALSE,50000)

#in fact, the mechanism to set the "names" is the same as for vectors
names(l) <- c("name", "unemployed", "salary")

#access single elements
l[[1]]
l$name
l["name]
l$sal #it is even allowed to abbreviate the names if it is unique

#generate a "sub" list
l[c(1,3)]
l[c("name","salary")]
l[1]

#"fields" can be added dynamically
l$department <- "IT"
l[["position"]] <- c("consultant","developer")
#note that this can create gaps and unnamed fields
l[[8]] <- TRUE

好像只有在$后面的才能以省略

R语言中的factor

f <- factor(c("A","B","C","A","B","A","A"), ordered = T)
attributes(f)
levels(f)
summary(f)

#to rename a category
levels(f)[1] <- "a"

#to convert to a numeric type
as.numeric(f)
#or:
attributes(f) <- NULL

R语言的data.frame

#create a data frame manually
df <- data.frame(x=runif(20), y=runif(20), type=as.factor(runif(20) > 0.5))
str(df)

#create a new "feature"
df$z <- df$x * df$y
df

#sort by a feature
permutation <- order(df$x)
df <- df[permutation,]

#remove features
toRemove <- c("x","y")
toRemoveLogical <- names(df) %in% toRemove
df <- df[,!toRemoveLogical]
df <- df[,!toRemoveLogical, drop= FALSE]
#better if only one feature is kept

#there is also the powerful "subset" function
#parameter "subset" works on rows
#parameter "subset" works on columns
subset(df, subset = x > 0.5, select = c(y,z))

什么是S3/S4 classes

不知??

Functions

如何定义一个function

nameOfMyFunction <- function(a,b){
return (a+b)
}

注意,return需要有圆括号,另外如果没有return的话,那就默认返回最后一个statement

如何定义函数的默认参数

myfunc <- function(range = 1 : myelin) range^2
myfunc(1:5)

mylen=10
myfunc()

mylen=5
myfunc()

rm(malen)
myfunc()

如何返回多于一个值

myfunc <- function(){
    list(result=42,additional="no errors",numberOfIterations=4)
}
ret <- myfunc()
ret$result
ret$numberOfIterations

补充

R里是否有预定义的变量

答案是有得如:
mtcars
Nile
iris
diamonds

如何连接两个strings

注意不能直接用“+”连接起来

paste("concatenate", "these", "strings")
paste("concatenate", "these", "strings", seq="")

也可以用paste0(…),他的效率比paste好一点点

如何标准输出

x <- 1:10
cat(sprintf("the sum of %d elements is %f\n", length(x), sum(x)))

如何生成随机数

hist(rnorm(1000))
hist(runif(1000))
hist(rbeta(1000,2,4))
hist(rbinom(1000,3,0.5))

Plotting

#histograms:
hist(rnom(1000))
#scatter plots:
plot(rnom(100), rnorm(100)
#line plots:
x <- seq(0, 2*pi, len=100)
plot(x, sin(x)^2+tan(x), type='l'

Numerical Measures

duration = faithful$eruptions
mean(duration)
median(duration)
quantile(duration)
quantile(duration,c(.37,.45,.99))
var(duration)   #variance

waiting = faithful$waiting
cov(duration,waiting)   #covariance

cor(duration, waiting)  #correlation coefficient
cov(duration, waiting)/(sd(duration)*sd(waiting))#standard deviations

概率分布

//待补

静态测试

//待补

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值