R的基本用法
R变量的命名格式
- 必须以字母开头
- 只能包含字母、数字、下划线和
.。 - 对大小写敏感
- 不能是保留关键字
数据类型(mode)
numeric- (10.5, 55, 787)integer- (1L, 55L, 100L, where the letter "L" declares this as an integer)complex- (9 + 3i, where "i" is the imaginary part)character(a.k.a. string)logical(a.k.a. boolean)
例如:mode(a) #numeric 而typeof(a) #double
types "integer" and "double" are returned as "numeric" mode.
class(), mode(), typeof() 三者的差异:
class() 对象的数据结构:vector、matrix、array、dataframe、list
mode() 对象数据类型。
typeof()查看数据元素类型,基本等同于mode(),比mode()更为详细
x <- 10.5
x <- 1000L
x <- 9i + 3
x <- "R is exciting"
x <- TRUE
注意
- TRUE/FALSE是全大写
- 复数是i,python里复数是j
- 要创建
integer变量,必须L在整数值后面使用字母;如果不加L那一定是numeric变量。
您可以使用以下功能从一种类型转换为另一种类型:
as.numeric()as.integer()as.complex()
x <- 1L
a <- as.numeric(x)
class(a)
min()andmax()函数可用于查找集合中的最小或最大数字sqrt()abs()ceiling(),floor()sign()正数返回1,负数返回-1,0返回0.
字符串
nchar()求字符串长度grepl()检查字符串中是否存在字符或字符序列,return TRUE/FALSE,grepl("H", str)paste()函数连接两个字符串paste(str1, str2)- 转义字符
\
注意:
"和'是等价的- 正常情况下
character就是用一行输出,如果加上cat()会按照代码块里的换行格式输出。
str <- "Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."
cat(str)
- 如果使用了转义字符,直接用变量名输出会显示
\。如果不像要\, 就用cat()。
、
Logical
注意是TRUE、FALSE, 可以用T、F代替。
operator
^Exponent%%取模%/%整除(余数部分不要)
赋值
<-<<-全局赋值- 也可以改变赋值运算符的方向。
x <- 3等于3 -> x
比较运算符
- ==
- !=
=
逻辑运算符
- 按位
&| - 逻辑
&&,||,!
其他运算符
:生成一组数x <- 1:10%in%Find out if an element belongs to a vectorx %in% y%*%矩阵乘法x <- Matrix1 %*% Matrix2
Vectors
向量默认是列向量
# Vectors
fruits <- c("banana", "apple", "orange")
vec_seq3 <- seq(1, 10, by = 3)
vec_pattern <- rep(1:3, times = 4) #123重复4次
vec_pattern2 <- rep(1:3, times = 4, each = 2) #112233重复4次
numbers <- 1:10 #默认间隔为1
numbers1 <- 1.5:6.5 #默认间隔为1,左闭右闭[]
numbers2 <- 1.5:6.3 #默认间隔为1,这里最后一个数是5.5
numbers <- seq(from=0, to=100, by=20) #生成其他间隔的序列数据
fruits[1]
fruits[c(1, 3)] #索引访问第1个元素、和第3个元素。R中索引从1开始。支持负索引。
fruits[1] <- "pear"
注意:
- 索引从1开始
1:10是左闭右闭的
向量计算
vec <- c(1, 2, 5)
vec * 2 #每个位置上的数都会*2
Vectors Functions
length()sort()
Factors
Factor 用来处理 categorize data.
four_seasons <- c("spring", "summer", "autumn", "winter") four_seasons_factor <- factor(four_seasons) #factor出来会变成字母序,可以指定levels
four_seasons_factor <- factor(four_seasons, levels = c("spring", "summer", "autumn", "winter"))
four_seasons_factor[1]
four_seasons_factor[1] <- "no_spring" #只能赋成levels里已经存在的factor
Factors Functions
length()输出factor的个数levels(data_factor)只想输出levels
数据类型转换
R 中向量里每个元素的类型是一样的,若不同,会强制转换成一致的。
character > numeric > logical
double > integer
Lists
List 可以包含多种数据类型
thislist <- list("apple", TRUE, 123)
thislist[1]
thislist[1] <- "blackcurrant"
mylist
typeof(mylist$first)
Lists Functions
length()%in%看一个元素是否在list中append()append(thislist, "orange", after = 2)- index(索引)的使用
thislist[2:5] - 组合两个list
list1 <- list("a", "b", "c")
list2 <- list(1,2,3)
list3 <- c(list1,list2)
矩阵
mat <- matrix(data = c(2, 4, 6, 7, 8, 10), nrow = 2, ncol = 3, byrow = FALSE) #默认按着列来排
mat[2,] #访问第二行
mat[,3] #访问第三列
mat[2,3]#访问(2,3)
mat[c(1,2),]#访问1,2行
newmatrix <- cbind(thismatrix, c("strawberry", "blueberry", "raspberry")) #column combination加上一列,list的长度必须和矩阵的行数相同
newmatrix <- rbind(thismatrix, c("strawberry", "blueberry", "raspberry")) #row combination
thismatrix <- thismatrix[-c(1), -c(1)] #删除第一行和第一列
一些函数
%in%看矩阵中有没有对应元素"apple" %in% thismatrixdim()看矩阵几行几列length()看矩阵一共有多少元素rbind()和rbind()也可以用于合并两个矩阵Matrix_Combined <- rbind(Matrix1, Matrix2)
矩阵计算函数
t(A) #取转置
diag(A) #square matrix 求对角
det(A)
solve(A) #inverse
eigen(A)
sum(A) #每个位置上的数的和
mean(Aˆ2) #其他运算符同理
Aˆ2 #每个位置上的数平方
A * B #对应位置上的数相乘
B %*% C #叉乘
Arrays
定义高维矩阵(数组)
arr <- array(1:24, c(4, 3, 2), dimnames = list(dim1, dim2, dim3))
arr[2,3,2]
arr[c(1),,1] #仍然可以使用雷同的访问方式
Dataframe
每一列可以数据类型不同,但是同一列里数据类型必须相同。
df <- data.frame(name = c("Alice", "Bob", "Carl"),
age = c(23, 34, 23),
marriage = c(TRUE, FALSE, TRUE),
color = c("red", "blue", "orange"))
#访问一列有三种方式
df[1]
df[["name"]]
df$name
#删除第一行和第一列
Data_Frame_New <- Data_Frame[-c(1), -c(1)]
Dataframe functions
summary(df)可以求df每一列的general统计数据cbind()和rbind()也可以用于合并两个dataframeNew_row_DF <- rbind(Data_Frame, c("Strength", 110, 110))ncol(df),nrow(df)来求列数和行数dim(df)length()
数值计算函数
sum(1:8)
prod(3:5) #product
min(c(1, 5, -10, 300))
max(c(9, 2, -2))
range(c(1, 5, -10, 300))
mean(1:10)
var(1:10)
sd(1:10)
median(1:10)
quantile(1:10)
factorial(4)
exp(0:3)
log(1:10)
round(3.833) #默认是四舍五入到整数
round(3.833, digits = 1)
ceiling(3.83)
floor(3.83)
choose(4, 2) #组合数
which(c(1, 6, -3, -7, 0) <= 0)
any(c(1, 6, -3, -7, 0) <= 0)
all(c(1, 6, -3, -7, 0) <= 0)
IF ELSE
和C++语法一样
if (b > a) {
print("b is greater than a")
} else if (a == b) {
print("a and b are equal")
} else {
print("a is greater than b")
}
WHILE
语法同C++
区别
- C++中是
continue, R里是next
FOR
#sequential index
for (x in 1:10) {
print(x)
}
#list
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
print(x)
}
#matrix
for (rows in 1:nrow(thismatrix)) {
for (columns in 1:ncol(thismatrix)) {
print(thismatrix[rows, columns])
}
}
#array
for(x in multiarray){
print(x)
}
FUNCTION
my_function <- function(fname = 'no_name') {
paste(fname, "Griffin")
return "hhhh"
}
my_function("Peter")
R中可以function里定义function
Outer_func <- function(x) {
Inner_func <- function(y) {
a <- x + y
return(a)
}
return (Inner_func)
}
output <- Outer_func(3) # To call the Outer_func
output(5) # To call Inner_func
全局变量
- 在函数之外定义的是全局变量
- 如果使用赋值运算符
<<-,则变量属于全局范围 - 如果要更改函数内的全局变量,请使用全局赋值运算符
lecture2上节课剩下的
x<-cbind(x1=3,x2=c(4:1,2:4))
dimnames(x)[[1]]<-letters[1:7]
n_col<-ncol(x)
col_sum<-rep(0,n_col)
for(j in 1:n_col){
col_sum[j]<-sum(x[,j])
}
col_sum
names(col_sum) <- colnames(x)
事实上,上面的代码可以直接用apply实现
R的基本用法的更多相关文章
- ruby 中%Q %q %W %w %x %r %s的用法
%Q 用于替代双引号的字符串. 当你需要在字符串里放入很多引号时候, 可以直接用下面方法而不需要在引号前逐个添加反斜杠 (\") >> %Q(Joe said: "Fr ...
- R语言︱list用法、批量读取、写出数据时的用法
列表是一种特别的对象集合,它的元素也由序号(下标)区分,但是各元素的类型可 以是任意对象,不同元素不必是同一类型.元素本身允许是其它复杂数据类型,比如,列表 的一个元素也允许是列表.例如: > ...
- [Ruby]转载: 关于ruby中 %Q, %q, %W, %w, %x, %r, %s 的用法
单引号内的内容,ruby会原样输出 双引号内的内容,ruby会解析 我们看个简单的例子,针对字符串 #{foo}test 我们分别用单引号核双引号操作 '#{foo}test' ...
- cmd for 用法
1:for命令及变量 基本格式: FOR /参数 %variable IN (set) DO command [command_parameters] %variable:指定一个单一字母可替换的参数 ...
- R语言︱函数使用技巧(循环、if族/for、switch、repeat、ifelse、stopifnot)
每每以为攀得众山小,可.每每又切实来到起点,大牛们,缓缓脚步来俺笔记葩分享一下吧,please~ --------------------------- 后续加更内容: 应用一:if族有哪些成员呢?- ...
- R语言︱构造新序列
1.数值构造函数rep与seq #数值构造rep与seq rep(1:4,each=2)#依次重复1:4两遍 rep(1:4,2) #注意,重复1:4两遍 seq(from=3,to=5,by=0.2 ...
- R语言︱文件读入、读出一些方法罗列(批量xlsx文件、数据库、文本txt、文件夹)
笔者寄语:小规模的读取数据的方法较为简单并且多样,但是,批量读取目前看到有以下几种方法:xlsx包.RODBC包.批量转化成csv后读入. R语言中还有一些其他较为普遍的读入,比如代码包,R文件,工作 ...
- python基础_格式化输出(%用法和format用法)
目录 %用法 format用法 %用法 1.整数的输出 %o —— oct 八进制%d —— dec 十进制%x —— hex 十六进制 1 >>> print('%o' % 2 ...
- python基础_格式化输出(%用法和format用法)(转载)
python基础_格式化输出(%用法和format用法) 目录 %用法 format用法 %用法 1.整数的输出 %o -- oct 八进制%d -- dec 十进制%x -- hex 十六进制 &g ...
- js2py 的用法
python调用js的方法 js2py的简单用法 import js2py js = """ function add(a, b) { return a + b } &q ...
随机推荐
- npm publish命令
npm publish . 注意后面有个点,否则会报错
- Spyglass CDC工具使用(二)
最近一直在搞CDC (clock domain crossing) 方面的事情,现在就CDC的一些知识点进行总结. 做CDC检查使用的是Spyglass工具.以下内容转载自:Spyglass检查之CD ...
- install package within python
import os os.system("pip install numpy") import subprocess subprocess.call(['pip3', 'insta ...
- consul 服务注册与更新
服务注册与发现是微服务架构中不可或缺的重要组件. 起初服务都是单节点的,不保障高可用性,也不考虑服务的压力承载,服务之间调用单纯的通过接口访问.直到后来出现了多个节点的分布式架构,起初的解决手段是在服 ...
- Unity_飞机大战记录总结
记录步骤:win+R→PSR.exe 一.竖屏设置 分辨率设为9:16 二.主控脚本 添加一个空节点,命名"游戏主控" 新建游戏的主控脚本,命名为MyGame.cs,方便管理(即, ...
- linux驱动设备分类
1. linux驱动设备分类 1.1 字符设备 -c 1.没有文件系统 2.应用程序和驱动程序之间进行数据交互时,数据是以"字节"进行数据交换,并且是按照固定的顺序传输的,数据是实 ...
- IBM MQ 配置SSL 连接
图示为思路: 下面介绍具体的步骤 参考文档: https://www.jianshu.com/p/2865965a42d9 http://www.hackdig.com/?01/hack-7976.h ...
- 抑制stable_secret读取关键信息
如何抑制stable_secret读取关键的"net.ipv6.conf.all.stable_secret"消息? 您可以/dev/null使用以下命令抑制额外的不需要的消息或将 ...
- RPA的市场定义和企业选型
RPA(Robotic Process Automation)译为机器人流程自动化,又可以称为数字化劳动力,是一种智能化软件,通过模拟并增强人类与计算机的交互过程,实现工作流程中的自动化.RPA具有对 ...
- 报错的大怨种来了--java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
频繁爆出这样的错误:java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual t ...