213人阅读 评论(0)

# 先看一下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

## 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

y <- if(x > 0) "y" else "no"

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

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中混合不同类型的值会怎么样呢

#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)

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又是如何使用索引的呢

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

#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))

# Functions

## 如何定义一个function

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

## 如何定义函数的默认参数

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

# 补充

mtcars
Nile
iris
diamonds

## 如何连接两个strings

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

## 如何标准输出

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

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：16993次
• 积分：665
• 等级：
• 排名：千里之外
• 原创：0篇
• 转载：0篇
• 译文：48篇
• 评论：3条
文章分类
最新评论