# 以ToothGrowth为例子，演示tidyverse实用的函数
library(tidyverse)
# 加载内置数据
data("ToothGrowth")
colnames(ToothGrowth)
str(ToothGrowth)
unique(ToothGrowth$supp)
unique(ToothGrowth$dose)
# 使用mutate函数生成标签变量
df <- ToothGrowth |> 
  mutate(剂量=ifelse(dose==0.5,"0.5mg",
                   ifelse(dose==1.0,"1.0mg","2.0mg"))) |> 
  mutate(补充喂养=ifelse(supp=="VC","维生素C","橙汁")) |> 
  group_by(补充喂养,剂量) |> 
  summarize(n=n(),
            mean=mean(len),
            sd=sd(len),
            max=max(len),
            min=min(len),
            median=median(len))
# write.csv(df,"df.csv",row.names = F)


# 查看帮助
?group_by
??dplyr
apropos("norm")

# 向量的运算
a <- c(1:20)
b <- 2*a
c=b-a

# 如果是不一样长的俩个向量运算
a <- c(1:20)
b <- c(1:10)
c <- a-b  #循环补齐。


# 向量的交、并、补
# 找两个向量的不同元素
a <- c(1:15)
b <- c(10:20)
setdiff(a,b)
setdiff(b,a)

# $(变量索引) 与[]（下标索引）
aa <- c("A","B","C","李思齐")
aa[c(1,3)]
aa[1:3]

# 生成数据框
age <- c(20,30,18,26)
name <- c(" 赵"," 钱"," 孙"," 李")
score <- c(99,65,77,88)
df <- data.frame(age=age,
                 name=name,
                 score=score)


# 索引[ , ]
df[2,2]
df[1:2,2:3]

# 两种方式生成新列(身高)
df <- df |> 
  mutate(height=c(180,176,189,167))

df2$height <- c(180,176,189,167)





         