Week 1 Tutor -- R语言入门(1)-- 变量
大小写注意
算数运算
** 或 2^3 次方
%/% 整除
%% 取余数
变量赋值
x<- x+3
删除变量:rm(x)
%>%:就是把左件的值发送给右件的表达式,并du作为右件表达式函数的第zhi一个参数,就是管道函数。
例如:
anscombe_tidy <- anscombe %>%mutate(observation = seq_len(n()))
以上代码等价于:
anscombe_tidy=mutate(anscombe,observation = seq_len(n()))
补充:
%<>%:与%>%类似,也是将左边的结果传递给右边的函数进行计算,不同的是这个操作符会将最后的结果
返回给最开始的变量
%>%操作符不会将结果传递给原始的x1变量,而%<>%操作符会在计算完成后,将结果传递给原始变量x2
%T>%:会将左边的结果传递给右边进行一些运算,但不会返回运算后结果,只会返回原始的结果或者说上
一级的结果
%$%:该操作符的左边通常不是一个变量,而是一个数据框或者列表,它可以将左边的矩阵或者数据框传
递到右边的函数进行运算
%in%:该操作符的意思是匹配的含义,相当于R中的match函数,其表达的意思是左边的元素在右边的向
量中是否存在,如果存在则返回TRUE,否则返回FALSE
数据类型
• numeric:
• double (real numbers): values like 2.3, 3.14, -5.7634 , …
• integer: values like 0,1,2, -4, …
• character: values like “GDDS”, ‘exe’
• logical: TRUE and FALSE (always capital letters)
• complex: we have nothing to do with it in this unit.
用typeof(x)来查看
Vector
Vector是最常用的数据类型,我们用到的所有object都是vector.
vector是具有一个或多个相同类型值的变量,例如,都是数值类。若不同系统会自动强制转换
• Vectors are created by c() function (concatenatation function)
• Also, they ca be created by vector() function: v <- vector(“numeric”, length=5)
• should contain objects of the same class
• if you put objects from different classes, an implicit coercion (the calss of value would be changed) will happen
• Creating variables using seq and rep.
v6 <- seq(from=3, to=10, by=2) functions.
创建/删除vector
V1 <- c(4,5,7)
V1 <- NULL
赋值
V1[2] <- 3
删除某一个元素
V1[-2] 删掉第二个元素
List
similar to a vector, but it could contain objects from different classes.
创建
L1<- list(2,”a”,3)
数字类型
X <- 1 double
X<- 1L int
改变数据类型
y <- as.numeric(x)
Factors
Factors are stored as integers
x <- factor(c("male", "fmale", "fmale", "male"))
总结各元素重复次数
summary(x)
总结那几个元素
levels(x)
没有的值
NA
空值的处理
Mean(x1,na.rm=TRUE)
Matrices
m <- matrix(nrow=2, ncol=3) #empty matrix with dimension
m <- matrix(c(1,3,6,2,8,4), nrow=2, ncol=3 )
Data Frames
是一种特殊类型的列表,其中列表中的每个元素都应该具有相同的长度。
Data Frames可以在每个列中存储不同的对象类。矩阵中每个元素都应该有相同的类。
创建 Data Frames
df <- data.frame(x,y,z)
命名
x <- c(3,5,7)
names(x) <- c("low", "med", "high")