1. R语言基础
变量赋值:
# Assign the value 42 to x
x <- 42
# 打印 x
x
# Assign a value to the variables my_apples and my_oranges
my_apples <- 5
my_oranges <- 6
# Add these two variables together
my_oranges + my_apples
# Create the variable my_fruit
my_fruit <- my_oranges + my_apples
数据类型:
# Declare variables of different types
my_numeric <- 42
my_character <- "universe"
my_logical <- FALSE
# Check class of my_numeric,输出为 "numeric"
class(my_numeric)
# Check class of my_character,输出为 "character"
class(my_character)
# Check class of my_logical,输出为 "logical"
class(my_logical)
2. 向量
向量创建:
#创建向量
numeric_vector <- c(1, 10, 49)
character_vector <- c("a", "b", "c")
boolean_vector <- c(TRUE, FALSE, TRUE)
可以使用names()函数为向量的元素命名:
#方法一
# 创建向量:Poker winnings from Monday to Friday
poker_vector <- c(140, -50, 20, -120, 240)
# 向量命名:Assign days as names of poker_vector
names(poker_vector) <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
#方法二
# Poker winnings from Monday to Friday
poker_vector <- c(140, -50, 20, -120, 240)
# The variable days_vector
days_vector <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
# Assign the names of the day to poker_vector
names(poker_vector) <- days_vector
向量相加:直接操作
A_vector <- c(1, 2, 3)
B_vector <- c(4, 5, 6)
# A_vector 和 B_vector 相加
total_vector <- A_vector + B_vector
# 打印 total_vector:5 7 9
total_vector
向量求和:sum()
poker_vector <- c(140, -50, 20, -120, 240)
roulette_vector <- c(-24, -50, 100, -350, 10)
# 对poker_vector求和:230
total_poker <- sum(poker_vector)
# 对total_roulette求和:-314
total_roulette <-sum(roulette_vector)
#比较两个sum的大小:输出TRUE 或者 FALSE
total_poker > total_roule