R语言学习(5)-字符串和因子
【摘要】 字符串和因子
1.字符串
创建字符串
> c("HELLO","WORLD")
[1] "HELLO" "WORLD"
使用paste函数连接字符串
> paste(c("hello","hi"),"world")
...
字符串和因子
1.字符串
创建字符串
> c("HELLO","WORLD")[1] "HELLO" "WORLD"
使用paste函数连接字符串
> paste(c("hello","hi"),"world")[1] "hello world" "hi world"
> paste(c("hello","hi"),"world",sep="-")[1] "hello-world" "hi-world"> paste(c("hello","hi"),"world",collapse="!")[1] "hello world!hi world"> paste0(c("hello","hi"),"world") #paste0函数能去掉分隔符[1] "helloworld" "hiworld"
toString函数打印字符串
> x[1] 1 4 9 16 25> toString(x)[1] "1, 4, 9, 16, 25"> toString(x,width=2) #width表示限制字符长度[1] "1,...."
toupper、tolower函数更改大小写
> toupper("hello world!")[1] "HELLO WORLD!"> tolower("HELLO WORLD!")[1] "hello world!"
使用substring、substr截取字符串
使用strsplit分割字符串
2.格式化数字
formatC函数
> pow <- 1:3> (power_of_e <- exp(pow))[1] 2.718282 7.389056 20.085537> formatC(power_of_e)[1] "2.718" "7.389" "20.09"> formatC(power_of_e,digits=3) #保留三个数字[1] "2.72" "7.39" "20.1"> formatC(power_of_e,digits=3,width=10) #在前面添加空格[1] " 2.72" " 7.39" " 20.1"> formatC(power_of_e,digits=3,format="e") #科学计数法[1] "2.718e+00" "7.389e+00" "2.009e+01"> formatC(power_of_e,digits=3,flag="+") +前面加上+[1] "+2.72" "+7.39" "+20.1"
sprintf函数
> sprintf("%s %d %e", "Euler's constant to the power",pow,power_of_e)[1] "Euler's constant to the power 1 2.718282e+00"[2] "Euler's constant to the power 2 7.389056e+00"[3] "Euler's constant to the power 3 2.008554e+01"
还有format和prettyNum函数用于格式化数字
3.因子:因子是一个用于存储类别变量的特殊的变量类型,有时像字符串,有时像整数
创建因子
数据框自动创建因子
> (heights <- data.frame(height_cm = c(153,181,150,172,165),gender = c("female","male","male","female","male")))height_cm gender1 153 female2 181 male3 150 male4 172 female5 165 male> class(heights$gender)[1] "factor"> heights$gender[1] female male male female maleLevels: female male #female和male称为因子水平
factor函数创建因子
> gender_char <- c("female","male","male","female","male")> (gender_factor <- factor(gender_char))[1] female male male female maleLevels: female male
文章来源: blog.csdn.net,作者:冰水比水冰,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/luoyhang003/article/details/38349401
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)