R语言基础语法大全
目录
1. 基本操作
1.1 赋值
1
2
x <- 10 # 使用箭头赋值
y = 20 # 使用等号赋值
1.2 打印
1
2
print(x)
cat("x的值为:", x, "\n")
1.3 查看数据类型
1
class(x) # 查看数据类型
2. 数据类型
2.1 数值型 (Numeric)
1
num <- 3.14
2.2 字符型 (Character)
1
char <- "Hello, R!"
2.3 逻辑型 (Logical)
1
log <- TRUE
2.4 因子型 (Factor)
1
factor_var <- factor(c("male", "female", "male"))
2.5 向量 (Vector)
1
vec <- c(1, 2, 3, 4, 5)
2.6 矩阵 (Matrix)
1
mat <- matrix(1:9, nrow = 3, ncol = 3)
2.7 数据框 (Data Frame)
1
2
3
4
df <- data.frame(
Name = c("Alice", "Bob", "Charlie"),
Age = c(25, 30, 35)
)
2.8 列表 (List)
1
lst <- list(name = "John", age = 25, scores = c(85, 90, 95))
3. 基本控制流
3.1 条件语句
1
2
3
4
5
if (x > 0) {
print("x是正数")
} else {
print("x是非正数")
}
3.2 循环语句
3.2.1 For循环
1
2
3
for (i in 1:5) {
print(i)
}
3.2.2 While循环
1
2
3
4
5
i <- 1
while (i <= 5) {
print(i)
i <- i + 1
}
3.2.3 Repeat循环
1
2
3
4
5
6
i <- 1
repeat {
print(i)
i <- i + 1
if (i > 5) break
}
4. 函数
4.1 定义函数
1
2
3
4
5
add <- function(a, b) {
return(a + b)
}
result <- add(5, 3)
print(result)
4.2 内置函数
1
2
3
sum(vec) # 计算向量和
mean(vec) # 计算均值
sd(vec) # 计算标准差
5. 数据操作
5.1 索引和切片
1
2
3
vec[2] # 提取第二个元素
df[1, ] # 提取第一行
df[, "Age"] # 提取Age列
5.2 子集选择
1
subset(df, Age > 25)
5.3 数据排序
1
sorted_df <- df[order(df$Age), ]
6. 可视化
6.1 绘制基础图形
1
plot(vec, type = "o", col = "blue", main = "简单折线图")
6.2 直方图
1
hist(vec, col = "green", main = "直方图")
6.3 条形图
1
barplot(table(factor_var), col = "red", main = "条形图")
7. 包管理
7.1 安装包
1
install.packages("ggplot2")
7.2 加载包
1
library(ggplot2)
7.3 查看已安装包
1
installed.packages()
8. 文件操作
8.1 读写CSV文件
1
2
write.csv(df, "data.csv")
new_df <- read.csv("data.csv")
8.2 读写Excel文件
1
2
3
4
5
6
7
8
9
10
install.packages("readxl")
library(readxl)
# 读取Excel文件
data <- read_excel("data.xlsx")
# 写入Excel文件
install.packages("writexl")
library(writexl)
write_xlsx(df, "output.xlsx")
8.3 读写RData文件
1
2
save(df, file = "data.RData")
load("data.RData")
9. 日期和时间
1
2
3
Sys.Date() # 当前日期
Sys.time() # 当前时间
as.Date("2024-11-24") # 转换为日期对象
10. 调试
10.1 查看对象
1
ls()
10.2 删除对象
1
rm(x)
10.3 清空环境
1
rm(list = ls())