R-变量

变量不需要声明,

常用的变量有:

变量类型 定义 例子 例子效果
 logical  逻辑型:TRUE , FALSE  v<-TRUE; print(class(v))  "logical"
 numeric  数字型:23.4, 2 ,  v<-23.5;print(class(v))  "numeric"
 integer  整型:2L, 0L  v<-2L;print(class(v))  "numeric"
 complex  复合型  v<-3+2i;print(class(v))  "complex"
 character  字符型:'a',"FALSE"  v<-"TRUE";print(class(v))  "character"
 raw  原型:"Hello" 被存储为 48 65 6c 6c 6f  v<-charToRaw("Hello"); print(class(v)); print(v)

[1] "raw"
[1] 48 65 6c 6c 6f

 vectors    apple<-c("red","green"); print(apple); print(class(apple))  

[1] "red" "green"
[1] "character"

 list  列表型  list1<-list(c(2,5,3),21.3,sin);print(list1); print(class(list1))  

[[1]]
[1] 2 5 3

[[2]]
[1] 21.3

[[3]]
function (x) .Primitive("sin")

################

[1] "list"

 Matrices 矩阵型 M=matrix(c('a','a','b'),nrow=2,ncol=3,byrow=TRUE); print(M)  

      [,1] [,2] [,3]
[1,] "a" "a" "b"
[2,] "a" "a" "b"

 array  数组型

#包含两个元素的数组,每个元素为2x3个矩阵

a <- array(c('green','yellow','e'),dim = c(2,3,2));
print(a)

 

, , 1

[,1] [,2] [,3]
[1,] "green" "green" "green"
[2,] "yellow" "yellow" "yellow"

, , 2

[,1] [,2] [,3]
[1,] "green" "green" "green"
[2,] "yellow" "yellow"  "yellow"

 factor

 因子: 它将向量与向量中元素的不同值一起存储为标签。 标签总是字符,

不管它在输入向量中是数字还是字符或布尔等。

 

apple_colors<-c('green','green','yellow','red');
factor_apple<-factor(apple_colors);
print(factor_apple);
print(class(factor_apple));
print(nlevels(factor_apple))

 

[1] green green yellow red
Levels: green red yellow
[1] "factor"
[1] 3

 data.frame   数据帧:表格数据对象  

BMI <- data.frame(
gender = c("Male", "Male","Female"),
height = c(152, 171.5, 165),
weight = c(81,93, 78),
Age = c(42,38,26)
)
print(BMI)

gender height weight Age
1 Male 152.0 81 42
2 Male 171.5 93 38
3 Female 165.0 78 26

原文地址:https://www.cnblogs.com/Elanlalala/p/10486102.html