第三章 类和变量

发布时间 2023-08-13 09:04:41作者: 昵称已经被使用

第三章 类和变量

3.1 类

R 中的所有变量都有一个类,表明此变量属于什么类型。值得的注意是,所有的变量除了类之外,还有一个内部存储类型(通过 typeof 访问)、一个模式(mode),以及一个存储模式(storage.mode)。

R 有四种不同的函数能告诉你变量的类型是什么,即 class、typeof、mode 和 storage. mode。对于某些变量类型,这些函数给出的答案都相同,但对于其他的函数则有点不同, 这让事情变得有点复杂。

对于绝大部分你所编写的代码,你只需关心其 class 类型。class 唯一不能帮你的是在检 查矩阵或数组时,变量是否包含数字或字符(或其他类型)。在这种情况下,你可以使用 其他三种类型的函数之一,或只调用 is.* 函数(例如 is.numeric)中的一个。

数据类型 class typeof mode storage.mode
Logical logical logical logical logical
Integer integer integer numeric integer
Floating Point numeric double numeric double
Complex complex complex complex complex
String character character character character
Raw byte raw raw raw raw
Categorical factor integer numeric integer
Null NULL NULL NULL NULL
Logical Matrix matrix logical logical logical
Numeric Matrix matrix double numeric double
Character Matrix matrix character character characte
Logical Array array logical logical logical
Numeric Array array double numeric double
Character Array array character character character
List list list list list
Data Frame data.frame list list list
Function function closure function function
Environment environment environment environment environment
Expression expression expression expression expression
Call call language call language
Formula formula language call language

3.2不同类型的数字类

R 包含三种不同类别的数值变量:浮点值 numeric、整数 integer 和复数 complex。可通过检查变量的类型 class 把它们分辨出来

options(digits=n) 来设置全局默认选项,其中 n 在 1 和 22 之间,设置打印到小数点后第n位

> class(sqrt(1:10))
[1] "numeric"
> class(1) # 尽管只有一个数字,这也是一个 numeric 
[1] "numeric"
> class(1L) # 添加L后缀把数字变为整型
[1] "integer"
> class(1:5) # 冒号操作符返回的值是 numeric ,除非所有值都是整数
[1] "integer"
> class(3 + 1i)        #"i" 创建了复数的虚部
[1] "complex"

请注意,即使把 R 程序安装在 64 位操作系统上,所有的浮点数仍是 32 位 的(“双精度”),而 16 位(“单精度”)的数字是不存在的。

3.2.1格式化数字

formatC 可让你使用 C 语言的格式化风格来指定使用固定型或科学型的格式、小数的位数以及输出的宽度。无论使用哪种选项,输入都应该是 numeric 类型(包括数组),且输出是 character 字符向量或数组:

> pow <- 1:3
> (powers_of_e <- exp(pow))
[1]  2.718282  7.389056 20.085537
> formatC(powers_of_e)
[1] "2.718" "7.389" "20.09"
> formatC(powers_of_e, digits = 3)
[1] "2.72" "7.39" "20.1"
> formatC(powers_of_e, digits = 3, width = 10) 
[1] "      2.72" "      7.39" "      20.1"
> formatC(powers_of_e, digits = 3, format = "e")
[1] "2.718e+00" "7.389e+00" "2.009e+01"
>formatC(powers_of_e, digits = 3, flag = "+") 
[1] "+2.72" "+7.39" "+20.1"

sprint 的第一个参数指定了一个格式化字符串,其中包括其他值的占位符。:%s 代 表另一个字符串,%f 和 %e 分别代表固定型格式和科学型格式的浮点数,%d 表示整数。其 他参数的值将替换占位符。

> sprintf("%s %d = %f", "Euler's constant to the power", pow, powers_of_e)
[1] "Euler's constant to the power 1 = 2.718282" 
[2] "Euler's constant to the power 2 = 7.389056" 
[3] "Euler's constant to the power 3 = 20.085537"
> 
> sprintf("To three decimal places, e ^ %d = %.3f", pow, powers_of_e)
[1] "To three decimal places, e ^ 1 = 2.718" 
[2] "To three decimal places, e ^ 2 = 7.389" 
[3] "To three decimal places, e ^ 3 = 20.086"

format 提供的格式化字符串的语法稍有不同,与 formatC 的用法基本类似。而 prettyNum 则非常适合于格式化那些非常大或非常小的数字:

> format(powers_of_e)
[1] " 2.718282" " 7.389056" "20.085537"
> format(powers_of_e, digits = 3) 
[1] " 2.72" " 7.39" "20.09"
> format(powers_of_e, digits = 3, trim = TRUE) 
[1] "2.72"  "7.39"  "20.09"

3.3 其他通用类

向量还有其他四个类,它们分别是:逻辑类logical,用于存储文本的字符 character,存储类别数据的因子 factor,以及较罕见的存储二进制数据的原始值 raw。

3.3.1逻辑类

TRUE 和 FALSE 是 R 中的保留字:你不能创建以它们命名的变量(但可使用它们的小写或大小写混合,如 True)。当你启动 R 时,变量 T 和 F 已被系统默认定义为 TRUE 和 FALSE。虽然这能让你少打点字,但也会造成很大的问题。T 和 F 不是保留字,因此用户可以重新定义它们。

3.3.2字符(串)

> class(c('a', 'b', 'cc'))
[1] "character"

请注意,和某些语言不同,R 不区分整个字符串和单个字符——只包含一个字符的字符串与其他字符串的处理相同。与一些低级语言不同,你无需用空字符(\0)来终止字符串。 事实上,把这样一个字符加进字符串中也是错误的。

函数 描述
nchar(x) 计算x中的字符数量
substr(x, start, stop) 提取或替换一个字符串向量中的子串
grep(pattern, x, ignore.case = FALSE, fixed = FALSE) 在x中搜索某种模式。若fixed=FALSE, 则pattern为一个正则表达式。若 fixed=TRUE,则pattern为一个文本字 符串。返回值为匹配的下标
sub(pattern, replacement, x, ignore.case=FALSE, fixed=FALSE) 在x中搜索pattern,并以文本 replacement将其替换。若fixed=FALSE, 则pattern为一个正则表达式。若 fixed=TRUE,则pattern为一个文本字 符串
toupper(x) 转换为大写
tolower(x) 转换为小写
strsplit(x, split, fixed=FALSE) 在split处分割字符向量x中的元 素。若fixed=FALSE,则 pattern为一个正则表达式。若 fixed=TRUE,则pattern为 一个文本字符
paste(…, sep="") 连接字符串,分隔符为sep
length(x) 返回对象x的长度值
seq(from, to, by) 根据参数的要求生成一个序列
rep(x, n) 将x重复n次
cut(x, n) 将连续型变量x分割为有着n个水平的因子,使用选项 ordered_result = TRUE以创建一个有序型因子
pretty(x, n) 创建美观的分割点。通过选取 n+1个等间距的取整值,将一 个连续型变量x分割为n个区间。绘图中常用。
cat(... , file ="myfile", append =FALSE) 连接...中的对象,并将其输出到屏幕上或文件中(如果声明了一个的话)

3.3.2.1创建和打印字符串

字符向量可用 c 函数创建。我们可以用单引号或双引号把字符串引用起来,只 要引号之间匹配即可。不过,使用双引号更为标准:

> c("I am a boy")
[1] "I am a boy"

paste 函数能生成不同字符串。在它传入的参数向量中,每个元素都能自我循环以达到最长的矢量长度,然后字符串就被拼接在一起,中间以空格分开。可以使用参数 sep 更改分隔符,或使用相关的 paste()函数去掉分隔符。所有的字符串被组合后,可使用 collapse 参数把结果收缩成一个包含所有元素的字符串:

> paste(c("red", "yellow"), "lorry") 
[1] "red lorry"    "yellow lorry"
> paste(c("red", "yellow"), "lorry", sep = "-")
[1] "red-lorry"    "yellow-lorry"
> paste(c("red", "yellow"), "lorry", collapse = ", ")
[1] "red lorry, yellow lorry"
> paste0(c("red", "yellow"), "lorry")
[1] "redlorry"    "yellowlorry"
> paste(1:25, "lorry") 
 [1] "1 lorry"  "2 lorry"  "3 lorry"  "4 lorry" 
 [5] "5 lorry"  "6 lorry"  "7 lorry"  "8 lorry" 
 [9] "9 lorry"  "10 lorry" "11 lorry" "12 lorry"
[13] "13 lorry" "14 lorry" "15 lorry" "16 lorry"
[17] "17 lorry" "18 lorry" "19 lorry" "20 lorry"
[21] "21 lorry" "22 lorry" "23 lorry" "24 lorry"
[25] "25 lorry"
> paste(1:25, 1:22) 
 [1] "1 1"   "2 2"   "3 3"   "4 4"   "5 5"   "6 6"  
 [7] "7 7"   "8 8"   "9 9"   "10 10" "11 11" "12 12"
[13] "13 13" "14 14" "15 15" "16 16" "17 17" "18 18"
[19] "19 19" "20 20" "21 21" "22 22" "23 1"  "24 2" 
[25] "25 3" 
> paste(1, 1) 
[1] "1 1"

toString 函数是 paste 的变种,它在打印向量时非常有用。它使用逗号和空格分隔每个元 素,且可限制打印的数量。

> x <- (1:15) ^ 2 
> toString(x)
[1] "1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225"
> 
> toString(x, width = 40)
[1] "1, 4, 9, 16, 25, 36, 49, 64, 81, 100...."

cat 是一个低级函数,工作原理类似于 paste,不过格式功能更少。你将很少直接调用它。

> cat(c("red", "yellow"), "lorry")
red yellow lorry

通常情况下,当字符串打印到控制台时,它们会以双引号括起来。如果对它们使用 noquote 函数,就可以去掉这些引号。

> x <- c("I","am","a","boy")
> y <- noquote(x)
> x
[1] "I"   "am"  "a"   "boy"
> y
[1] I   am  a   boy

3.3.2.2特殊字符

有一些特殊的字符可以被包含在字符串中。

可以通过 \t 插入一个制表符。

> print("foo\tbar")
[1] "foo\tbar"
> cat("foo\tbar", fill = TRUE)
foo	bar

将光标移动到下一行是通过打印换行符 \n 完成的,在R 中,不要使用 \r 或 \r\n 来打印换行符,因为 \r 会将光标移动到当前行的开始并覆盖你所写的内容:

> cat("foo\nbar", fill = TRUE)
foo
bar

注意:在 R 的内部代码中,空字符 \0 用于终止字符串。然而,显式地把它们包含在字符串中是错误的

打印反斜杠符时需要连续输入两个反斜杠符,以免被误认为特殊字符。

> cat("foo\\bar", fill = TRUE)
foo\bar

如果我们需要在字符串中使用双引号,那么双引号符前必须加一个反斜杠来转义。同样地,如果要在字符串中使用单引号,则单引号需要被转义:

> cat("foo\"bar", fill = TRUE)
foo"bar
> cat('foo\'bar', fill = TRUE)
foo'bar

如果在被双引号引用的字符串中使用单引号,或在被单引号引用的字符串中使用双引号,则并不需要对其进行转义:

> cat("foo'bar", fill = TRUE)
foo'bar
> cat('foo"bar', fill = TRUE)
foo"bar

通过打印报警符 \a 能让我们的电脑发出提示声(beep),不过 alarm 函数也能完成此功能 且可读性更好。

cat("\a")
alarm()

3.3.2.3更改大小写

使用 toupper 和 tolower 函数能把字符串中的字符全部转换为大写或小写:

> toupper("I'm Shouting")
[1] "I'M SHOUTING"
> tolower("I'm Whispering")
[1] "i'm whispering"

3.3.2.4截取字符串

有两个函数可用于从字符串中截取子串:substring 和 substr。对 substring 来说,输出的长度与最长的输入一样;而对substr 来说,输出的长度只与第一个输入的相等:

> woodchuck <- c(   "How much wood would a woodchuck chuck",   "If a woodchuck could chuck wood?",   "He would chuck, he would, as much as he could",   "And chuck as much wood as a woodchuck would",   "If a woodchuck could chuck wood." )
> substring(woodchuck, 1:6, 10)
[1] "How much w" "f a woodc"  " would c"  
[4] " chuck "    " woodc"     "uch w"     
> substr(woodchuck, 1:6, 10)
[1] "How much w" "f a woodc"  " would c"  
[4] " chuck "    " woodc" 

3.3.2.5分割字符串

strsplit 则正好相反,它在指定的某些点上分割字符串。

> strsplit(woodchuck, " ", fixed = TRUE)
[[1]]
[1] "How"       "much"      "wood"      "would"    
[5] "a"         "woodchuck" "chuck"    

[[2]]
[1] "If"        "a"         "woodchuck" "could"    
[5] "chuck"     "wood?"    

[[3]]
 [1] "He"     "would"  "chuck," "he"     "would,"
 [6] "as"     "much"   "as"     "he"     "could" 

[[4]]
[1] "And"       "chuck"     "as"        "much"     
[5] "wood"      "as"        "a"         "woodchuck"
[9] "would"    

[[5]]
[1] "If"        "a"         "woodchuck" "could"    
[5] "chuck"     "wood."  

注意:strsplit 返回的是列表(而非字符向量或矩阵)。这是因为它的结果可能由不同长度的字符向量组成。当你只传入一个字符串时,这种情况很容易被忽视。

3.3.3因子

请注意,即使“male”是 gender 中的第一个值,第一个水平仍是“female”。默认情况下, 因子水平按字母顺序分配。在底层,因子的值被存储为整数而非字符。

采取整数而非字符文本的存储方式,令内存的使用非常高效,尤其当出现大量重复字符串时。一个因子包含 的值比同等字符占用更少的内存。sample 返回一个字符向量(这是使用 as.factor 转换而成的),而 object.size 则返回每个对象的内存分配大小:

> gender_char <- sample(c("female", "male"), 10000, replace = TRUE)
> gender_fac <- as.factor(gender_char)
> object.size(gender_char)
80160 bytes
> object.size(gender_fac)
40560 bytes

请注意,32 位和 64 位系统中变量所占用的内存数量是不一样的,所以在不同情况下 object.size 将返回不同的值。

3.3.3.1创建因子

使用函数factor()将原始表示类别的字符串映射到整数上

diabetes <- factor(diabetes)

创建有序的因子型向量

status <- factor(status,ordered=TRUE)

> (heights <- data.frame(   height_cm = c(153, 181, 150, 172, 165, 149, 174, 169, 198, 163),   gender = c(     "female", "male", "female", "male", "male",    "female", "female", "male", "male", "female"  ) ))
   height_cm gender
1        153 female
2        181   male
3        150 female
4        172   male
5        165   male
6        149 female
7        174 female
8        169   male
9        198   male
10       163 female

因子中的每个值都是一个字符串,它们被限制为指定值或缺失值。如果我们把不同的字符串添加到变量中,此项约束会提示且赋值为NA:

> heights$gender[1] <- "Female" 
Warning message:
In `[<-.factor`(`*tmp*`, 1, value = c(NA, 2L, 1L, 2L, 2L, 1L, 1L,  :
  invalid factor level, NA generated
> heights$gender 
 [1] <NA>   male   female male   male   female female
 [8] male   male   female
Levels: female male

选项“female”和“male”被称为因子水平,它能用 levels 函数查询到:

> levels(heights$gender)
[1] "female" "male"

水平的级数(相当于因子 level 的 length)可由 nlevel 函数查询到:

> nlevels(heights$gender)
[1] 2

除了使用数据框在内部自动创建因子之外,也可以使用 factor 函数创建它。它的第一个参数(唯一的强制要求)是一个字符向量:

> gender_char <- c(   "female", "male", "female", "male", "male",   "female", "female", "male", "male", "female" )
> (gender_fac <- factor(gender_char))
 [1] female male   female male   male   female female
 [8] male   male   female
Levels: female male

3.3.3.2更改因子水平

可以通过指定 levels 参数来更改因子被创建时水平的先后顺序:

> factor(gender_char, levels = c("male", "female"))
 [1] female male   female male   male   female female
 [8] male   male   female
Levels: male female

如果想在因子创建之后再改变因子水平的顺序,就再次使用 factor 函数,这时它的参数是当前的因子(而不是字符向量):

> factor(gender_char, levels = c("male", "female"))
 [1] female male   female male   male   female female
 [8] male   male   female
Levels: male female

注意:不能使用 levels 函数直接改变因子的水平值。因为这将重新为每一个水平打上标签,更改数据值。

relevel 函数是另一种改变因子水平顺序的方法。在这种情况下,你只需指定第一个水平值。

> relevel(gender_fac, "male")
 [1] female male   female male   male   female female
 [8] male   male   female
Levels: male female

3.3.3.3去掉因子水平

在数据集清理的过程中,可能需要去掉所有与因子水平对应的数据。

> getting_to_work <- data.frame(   mode = c(     "bike", "car", "bus", "car", "walk",     "bike", "car", "bike", "car", "car"),   time_mins = c(25, 13, NA, 22, 65, 28, 15, 24, NA, 14) )
> 
> (getting_to_work <- subset(getting_to_work, !is.na(time_mins)))
   mode time_mins
1  bike        25
2   car        13
4   car        22
5  walk        65
6  bike        28
7   car        15
8  bike        24
10  car        14

请看 mode 一列,其中只有三个不同值,而因子水平却是 four。我们可以使用 unique 函数看清这一点:

> unique(getting_to_work$mode)
[1] bike car  walk
Levels: bike bus car walk

如果要删除未使用的水平因子,我们可以使用 droplevels 函数。它接受因子或是数据框作 为参数。对后者来说,它将丢弃输入因子中所有未使用的水平。

> getting_to_work$mode <- droplevels(getting_to_work$mode)
> getting_to_work <- droplevels(getting_to_work) 
> unique(getting_to_work$mode)
[1] bike car  walk
Levels: bike car walk

3.3.3.4有序因子

使用 ordered 函数(或通过给 factor 传入 order = TRUE 参数)可实现存储为一个按顺序排列的因子。

> happy_choices <- c("depressed", "grumpy", "so-so", "cheery", "ecstatic")  
> happy_values <- sample(   happy_choices,   10000, replace = TRUE )
> happy_fac <- factor(happy_values, happy_choices) 
> head(happy_fac)
[1] grumpy    depressed ecstatic  depressed ecstatic 
[6] so-so    
Levels: depressed grumpy so-so cheery ecstatic
> happy_ord <- ordered(happy_values, happy_choices) 
> head(happy_ord)
[1] grumpy    depressed ecstatic  depressed ecstatic 
[6] so-so    
5 Levels: depressed < grumpy < so-so < ... < ecstatic

一个有序的因子还是因子,但一般的因子却不一定是有序的

> is.factor(happy_ord)
[1] TRUE
> is.ordered(happy_fac)
[1] FALSE

3.3.3.6将连续变量转换为类别

一个汇总数值变量的方法是计算有多少个值落入不同的“组”(bins)中,cut 函数能将数值变量切成不同的块,然后返回一个因子。它通常使用 table 函数得到每组数字的总和。(hist 函数能画出直方图,它也能实现这个功能,就像我们将在后面看到的包含在 plyr 包 中的 count 一样。

> ages <- 16 + 50 * rbeta(10000, 2, 3) 
> grouped_ages <- cut(ages, seq.int(16, 66, 10)) 
> head(grouped_ages)
[1] (16,26] (26,36] (16,26] (26,36] (26,36] (36,46]
5 Levels: (16,26] (26,36] (36,46] ... (56,66]
> table(grouped_ages)
grouped_ages
(16,26] (26,36] (36,46] (46,56] (56,66] 
   1840    3409    2962    1500     289 
> class(ages)
[1] "numeric"
> class(grouped_ages)
[1] "factor"

3.3.3.6将类别变量转换为连续变量

是把因子转换成数值变量,这在数据清理中非常有用。

> dirty <- data.frame(   x = c("1.23", "4..56", "7.89") )
> as.numeric(levels(dirty$x))[as.integer(dirty$x)]
[1] 1.23   NA 7.89
Warning message:
强制改变过程中产生了NA 

3.3.3.7生成因子水平

为了平衡数据,使到在每个水平上的数据点的数目相等,可用 gl 函数来生成因子。它最 简单的形式是:第一个整型参数为要生成的因子的水平数,第二个为每个水平需要重复的 次数。

> gl(3, 2)
[1] 1 1 2 2 3 3
Levels: 1 2 3
> gl(3, 2, labels = c("placebo", "drug A", "drug B"))
[1] placebo placebo drug A  drug A  drug B  drug B 
Levels: placebo drug A drug B
> gl(3, 1, 6, labels = c("placebo", "drug A", "drug B")) 
[1] placebo drug A  drug B  placebo drug A  drug B 
Levels: placebo drug A drug B

3.3.3.8合并因子

如果我们有多个类别变量,有时把它们合并成一个单一的因子是有用的,其中每个水平由 各个变量之间的交叉合并(使用 interaction 函数)组成:

> treatment <- gl(3, 2, labels = c("placebo", "drug A", "drug B")) 
> gender <- gl(2, 1, 6, labels = c("female", "male")) 
> interaction(treatment, gender)
[1] placebo.female placebo.male   drug A.female 
[4] drug A.male    drug B.female  drug B.male   
6 Levels: placebo.female ... drug B.male

3.3.4原始值

原始类 raw 存储向量的“原始”字节 2。每个字节由一个两位的十六进制值表示。它们主 要用于保存输入的二进制文件的内容,因而比较少见。使用 as.raw 函数可把 0 到 255 之间 的整数转换为原始值(raw)。此范围之外的数字将全部视为 0,分数和虚部也被丢弃。对于字符串,as.raw 则不起作用,而须使用 charToRaw 函数:

> as.raw(1:17)
 [1] 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11
> as.raw(c(pi, 1 + 1i, -1, 256))
[1] 03 01 00 00
Warning messages:
1: 强制改变时丢弃了虚数部分 
2: 在强制改变成原始值时,任何溢位值当作零来处理 
> (sushi <- charToRaw("Fish!"))
[1] 46 69 73 68 21
> class(sushi)
[1] "raw"

3.4 检查和更改类

3.4.1检查

接在命令提示符下,以交互的方式键入类 class 的函数名来检查变量是很有用的。但是 如果想在脚本中测试对象的类型,则最好用 is 函数,或针对某个类写的特定函数。大部分的类都会有自己的 is.* 函数。通常,直接调用它们比使用通用 is 函数稍显高效。

> is.logical(FALSE)
[1] TRUE
> is.character("aaa")
[1] TRUE

ls(pattern = "^is".baseenv())可查看base包中所有的is函数:

ls 列出所有的变量名,"^is" 是一个正则表达式,它意味着“匹配所有以 'is' 开头的字符串”,而 baseenv 函数则返回 base 包中所有的环境。

> ls(pattern = "^is",baseenv())
 [1] "is.array"                "is.atomic"       
 [3] "is.call"                 "is.character"     
 [5] "is.complex"              "is.data.frame"   
 [7] "is.double"               "is.element"       
 [9] "is.environment"          "is.expression"   
[11] "is.factor"               "is.finite"       
[13] "is.function"             "is.infinite"            
[15] "is.integer"              "is.language"            
[17] "is.list"                 "is.loaded"              
[19] "is.logical"              "is.matrix"              
[21] "is.na"                   "is.na.data.frame"       
[23] "is.na.numeric_version"   "is.na.POSIXlt"          
[25] "is.na<-"                 "is.na<-.default"        
[27] "is.na<-.factor"          "is.na<-.numeric_version"
[29] "is.name"                 "is.nan"                 
[31] "is.null"                 "is.numeric"             
[33] "is.numeric.Date"         "is.numeric.difftime"    
[35] "is.numeric.POSIXt"       "is.numeric_version"     
[37] "is.object"               "is.ordered"
[39] "is.package_version"      "is.pairlist"
[41] "is.primitive"            "is.qr"
[43] "is.R"                    "is.raw"
[45] "is.recursive"            "is.single"
[47] "is.symbol"               "is.table"
[49] "is.unsorted"             "is.vector"
[51] "isatty"                  "isBaseNamespace"
[53] "isdebugged"              "isFALSE"         
[55] "isIncomplete"            "isNamespace"
[57] "isNamespaceLoaded"       "isOpen"
[59] "isRestart"               "isS4"             
[61] "isSeekable"              "isSymmetric"     
[63] "isSymmetric.matrix"      "isTRUE" 

3.4.2更改

改变一个对象的类型。这就是所谓的转型(casting),大部分的 is* 函数 都有与之对应的 as* 函数。尽可能使用特定的 as* 函数而非单纯的 as 函数,因为它们通 常更有效。

> as(x, "numeric")
[1] 12.34
> as.numeric(x)
[1] 12.34

3.5变量

3.5.1创建变量

变量名←表达式

“表达式”部分可以包含多种运算符和函数

3.5.2变量的重编码

根据同一个变量(和/或其他变量)的现有值创建新值的过程。如:

  • 将一个连续型变量修改为一组类别值;
  • 将误编码的值替换为正确值;
  • 基于一组分数线创建一个表示及格/不及格的变量。

要重编码数据,可以使用R中的一个或多个逻辑运算符

3.5.3变量的重命名

方法1:调用一个交互式的编辑器: fix(leadership)

方法2:以编程方式, reshape包中有一个rename()函数

方法3:names()函数

3.6 检查变量

3.6.1print函数

当在控制台输入一个运算或者变量时,结果就被打印出来,因为 R 隐式调用了对象的 print 方法。大多情况下,“方法”(method)和“函数”(function) 是可以互换的。

大部分 print 函数的实现建立在调用底层的 cat 函数上(了解)

> 1 + 1
[1] 2
> print(1+1)
[1] 2

3.6.2summary函数

summary 函数就能为 不同的数据类型提供汇总信息。

数值变量会被汇总统计出平均数、中位数,以及一 些分位数(quantile)。
类别变量和逻辑向量将根据每个值的计算进行汇总。
多维对象与矩阵及数据框一样,都是通过列来汇总的。

> summary(num)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.00    5.75   10.50   10.50   15.25   20.00 

3.6.3head函数

如果数据框非常大,用 head 函数即可仅显示它的前几行

参数一是数据类型,参数二是想显示的行数,参数三是当没有行名,则用行号来代替

> df <-data.frame(1:100,101:200)
> head(df,10)
   X1.100 X101.200
1       1      101
2       2      102
3       3      103
4       4      104
5       5      105
6       6      106
7       7      107
8       8      108
9       9      109
10     10      110

类似的函数还有tail()仅显示它的后几行

3.6.4str函数

str 函数能显示对象的结构

> str(df)
'data.frame':	100 obs. of  2 variables:
 $ X1.100  : int  1 2 3 4 5 6 7 8 9 10 ...
 $ X101.200: int  101 102 103 104 105 106 107 108 109 110 ...

3.6.5unclass函数

unclass函数不会像print方法那样打印模糊了其内部结构,或忽略了一些有用的信息。

> unclass(df)
$X1.100
  [1]   1   2   3   4   5   6   7   8   9  10  11  12
 [13]  13  14  15  16  17  18  19  20  21  22  23  24
 [25]  25  26  27  28  29  30  31  32  33  34  35  36
 [37]  37  38  39  40  41  42  43  44  45  46  47  48
 [49]  49  50  51  52  53  54  55  56  57  58  59  60
 [61]  61  62  63  64  65  66  67  68  69  70  71  72
 [73]  73  74  75  76  77  78  79  80  81  82  83  84
 [85]  85  86  87  88  89  90  91  92  93  94  95  96
 [97]  97  98  99 100

$X101.200
  [1] 101 102 103 104 105 106 107 108 109 110 111 112
 [13] 113 114 115 116 117 118 119 120 121 122 123 124
 [25] 125 126 127 128 129 130 131 132 133 134 135 136
 [37] 137 138 139 140 141 142 143 144 145 146 147 148
 [49] 149 150 151 152 153 154 155 156 157 158 159 160
 [61] 161 162 163 164 165 166 167 168 169 170 171 172
 [73] 173 174 175 176 177 178 179 180 181 182 183 184
 [85] 185 186 187 188 189 190 191 192 193 194 195 196
 [97] 197 198 199 200

attr(,"row.names")
  [1]   1   2   3   4   5   6   7   8   9  10  11  12
 [13]  13  14  15  16  17  18  19  20  21  22  23  24
 [25]  25  26  27  28  29  30  31  32  33  34  35  36
 [37]  37  38  39  40  41  42  43  44  45  46  47  48
 [49]  49  50  51  52  53  54  55  56  57  58  59  60
 [61]  61  62  63  64  65  66  67  68  69  70  71  72
 [73]  73  74  75  76  77  78  79  80  81  82  83  84
 [85]  85  86  87  88  89  90  91  92  93  94  95  96
 [97]  97  98  99 100

3.6.6attributes 函数

attributes 函数能显示当前对像的所有属性列表

$names
[1] "X1.100"   "X101.200"

$class
[1] "data.frame"

$row.names
  [1]   1   2   3   4   5   6   7   8   9  10  11  12
 [13]  13  14  15  16  17  18  19  20  21  22  23  24
 [25]  25  26  27  28  29  30  31  32  33  34  35  36
 [37]  37  38  39  40  41  42  43  44  45  46  47  48
 [49]  49  50  51  52  53  54  55  56  57  58  59  60
 [61]  61  62  63  64  65  66  67  68  69  70  71  72
 [73]  73  74  75  76  77  78  79  80  81  82  83  84
 [85]  85  86  87  88  89  90  91  92  93  94  95  96
 [97]  97  98  99 100

3.6.7 View函数

为了可视化诸如矩阵和数据框之类的二维变量,View(请注意大写字母“V”)函数会把变 量(只读的)显示为电子表格(spreadsheet)。edit 和 fix 函数的工作方式与 View 类似, 但它允许手动更改数据值。但以这种方式编辑数据会失去所有的可追溯性而无法追踪数据的出处。

> View(df)