R 语言语法
- 查看当前目录 getwd()
- 切换指定目录 setwd()
1. Subsetting data选取数据
student[student$gender=='Female']
attach(student)
grade[Chinese>80,]
grade[Chinese>80 & Math>80,]
grade[Chinese>80 | Math>80,]
detach]
2. Sorting data
# sort by Chinese asc
order(grade$Chinese) # 排出升序的行号
oder(-grade$Chinese) # 进行降序的行号
grade[order(grade$Chinese),] #升序排序的dataFrame
# or use attach
attach(grade)
# sort by Chinese asc
grade[order(Chinese),]
# sort by Chinese asc, English des
grade[order(Chinese,-English),]
detach(grade)]
3. Merging data
# merging data by giving column names
total <- merge(student,grade,by="name")
head(total)
4. Aggregating Data
- aggregate(formula,data,FUN)
# compute the average Math grade by class
aggregate(Math~class, data=total,FUN=mean)
# compute the average grade by class and gender
aggregate(cbind(Chinese,Math,English,Science)~class+gender,data=total,FUN=mean)
Tips
paste(a,b,c) # 将所有内容组合出来,以sep=“ ”为分割
5. 自定义函数
Define a function:
function_name <- function (){
## Do something interesting
return(result)
}