参考《学习R》第七章
本章目标
- 从原有的字符串中构建新的字符串
- 特殊字符,如制表符,换行符
- 创建操作因子
字符串
创建和打印字符串
字符串可以用函数c创建,可以用单引号或者双引号把字符串引起来
paste
函数可以将不同字符按照设定的分隔符拼接在一起。
> 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', sep = ' ')
[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"
paste0
可以去掉分隔符。
更改大小写
toupper
和tolower
可以把字符串中的字符全部转换成大写或着小写。
> toupper("i'm shouting")
[1] "I'M SHOUTING"
> tolower("I'M SHOUTING")
[1] "i'm shouting"
截取字符串
截取字符串可以用:substring
和substr
大多数情况下可以通用。
> a <- "sdadsadasdas"
> a
[1] "sdadsadasdas"
> c <- substr(a, 3, 5)
> c
[1] "ads"
> d <- substring(a, 6, 9)
> d
[1] "adas"
分割字符串
函数strsplit
可以按照指定的分隔符分割字符串。
> a <- "dsadas dsadas dsadas wqoiwq qwjfhsafh"
> strsplit(a, " ", fixed = TRUE)
[[1]]
[1] "dsadas" "dsadas" "dsadas" "wqoiwq" "qwjfhsafh"
其中参数fixed = TRUE
表示分割的是固定长度的字符串而不是正则表达式。
特殊字符
R中有很多特殊字符,当然这在其它语言中也是有的。
\t
是为制表符
a <- "f\tb"
> cat(a)
f b
\n
是为换行符
\0
用于终止字符串
除此之外还有很多。
因子
因子用于存储类别变量(具体可以参考《R实战》。
创建因子
其实当你在把文本数据转换为数据框的时候,R会自动将类别数据转换成因子。
gender = c("female", "male", "female", "male", "male", "female", "female", "male", "male", "female")
> height_cm = c(153, 181, 150, 172, 165, 149, 174, 169, 198, 163)
> heights <- data.frame(height_cm, gender)
> heights
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
当你检查gender这一列的类时:
> class(heights$gender)
[1] "factor"
他是一个因子。
> heights$gender
[1] female male female male male female female male male female
Levels: female male
可以看到他有两个水平。
使用函数levels
可以查询因子水平而函数nlevel
可以查看水平的级数:
> levels(heights$gender)
[1] "female" "male"
> nlevels(heights$gender)
[1] 2
当然除了在数据框内部自动创建因子,也可以使用函数factor
创建。
更改因子水平
参数levels
可以更改因子被创建是的先后顺序。
> gender_cha <- c("female", "male", "female", "male", "male", "female", "female", "male", "male", "female")
> factor(gender_cha, levels = c("male", "female"))
[1] female male female male male female female male male female
Levels: male female
如果不定义默认按字母顺序。
这里要注意的是, 如果已经创建了因子的情况下想要更改因子水平要再次运行factor
函数而不是只运行levels
函数那样的话如果水平调换本来数据也会调换,male变成female。
删除因子水平
droplevels
函数可以删除未使用的因子水平
因子排序
ordered
或者给factor函数传入参数ordered = TRUE
合并因子
函数interaction
生成因子水平
gl
可以用来生成因子,第一个参数是要生成的因子的水平数,第二个为每个水平要重复的次数,如果要给水平命名使用参数:label
。
> gl(3, 2)
[1] 1 1 2 2 3 3
Levels: 1 2 3
> gl(3, 2, labels = c("a", "b", "c"))
[1] a a b b c c
Levels: a b c、
网友评论