首先安装了R,R studio
更改工作目录:
Session -> Set Working Directory
先创建一个script,执行:ctrl+enter
数据类型
数据类型 | 例子 |
---|---|
Logical | TRUE, FALSE |
Numeric(数字) | 12.3,5,999 |
Integer(整型) | 2L,34L,0L |
Complex(复合型) | 3 + 2i |
Character(字符) | ‘a’ , '“good”, “TRUE”, ‘23.4’ |
Raw(原型) | “Hello” 被存储为 48 65 6c 6c 6f |
数据容器
- vector
# Create a vector.
apple <- c('red','green',"yellow")
print(apple)
输出:
vector每个元素的数据类型是一样的
- list
# Create a list.
list1 <- list(c(2,5,3),21.3,sin)
结果:
list的元素可以是任意类型
- Matrices 矩阵
# Create a matrix.
M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
结果:
矩阵被限制在2维
- Arrays 数组
# Create an array.
a <- array(c('green','yellow'),dim = c(3,3,2))
- Factors 因子
因子是使用向量创建的r对象。 它将向量与向量中元素的不同值一起存储为标签。 标签总是字符,不管它在输入向量中是数字还是字符或布尔等。 它们在统计建模中非常有用。
使用factor()函数创建因子。nlevels函数给出级别计数。
我感觉这个有点像枚举类型
# Create a vector.
apple_colors <- c('green','green','yellow','red','red','red','green')
# Create a factor object.
factor_apple <- factor(apple_colors)
# Print the factor.
print(factor_apple)
print(nlevels(factor_apple))
- Data Frames 数据帧
数据帧是表格数据对象。 与数据帧中的矩阵不同,每列可以包含不同的数据模式。 第一列可以是数字,而第二列可以是字符,第三列可以是逻辑的。 它是等长度的向量的列表。
使用data.frame()函数创建数据帧。
# Create the data frame.
BMI <- data.frame(
gender = c("Male", "Male","Female"),
height = c(152, 171.5, 165),
weight = c(81,93, 78),
Age = c(42,38,26)
)
print(BMI)
结果: