菜鸡的R语言学习笔记——数据结构 Part 1

来源:互联网 发布:深圳赛维网络ceo陈文平 编辑:程序博客网 时间:2024/06/05 20:06
R version 3.4.2 (2017-09-28) -- "Short Summer"
Copyright (C) 2017 The R Foundation for Statistical Computing

Platform: x86_64-w64-mingw32/x64 (64-bit)

        起手式:R语言的循环,很锻炼一个人的那耐力,如果你不能做到非常非常非常持久,就请做到多用向量,少用循环,apply族的函数去拯救世界?但是我觉得我们需要开始正文,停下吐槽了。本文的主要知识点来源于《R统计建模与R软件》

      首先本文设计的数据结构包括(1)数字、字符与向量 (2)因子 (3)数组、向量与矩阵 (4)列表与数据框

      1 对象模式 属性 mode & length

      R语言基于对象,其对象有两种基本属性:mode 类 型 与 length 长度。这里介绍几个函数用于快速检测或者说得到相应数据类型的属性。

       1.1 mode() 函数

        #Get or set the type or storage mode of an object. 

        举例,定义x是一个1+2i的复数,然后相应的输出x的属性就是complex(复数)

> x<-complex(1,1,2)> x[1] 1+2i> mode(x)[1] "complex"

         同样再可以看看其他的相关输出

> x<-"caiji"> mode(x)[1] "character"> x<-NULL> mode(x)[1] "NULL"> x<-NA> mode(x)[1] "logical"> x<-TRUE> mode(x)[1] "logical"> x=232141434342314234> mode(x)[1] "numeric"
         1.2 typeof() 函数

         #typeof determines the (R internal) type or storage mode of any object

         这里typeof函数返回一个mode属性

> x1<-"caiji"> x2<-1431443234234> x3<-TRUE> x4<-214143413L> x5<-NULL> x6<-NA> x7<-412343.4214324234
> typeof(x1)[1] "character"> typeof(x2)[1] "double"> typeof(x3)[1] "logical"> typeof(x4)[1] "integer"> typeof(x5)[1] "NULL"> typeof(x6)[1] "logical"> typeof(x7)[1] "double"
           1.3 length() 函数和attributes()  attr() 函数

           length() 函数返回向量的长度,attributes(object) 函数返回对象的各种特殊属性组成的列表,但是不包含length和mode,以ggplot2函数的diamonds函数为例,其数据集的基本结构如下:

> library(ggplot2)> data("diamonds")> head(diamonds)# A tibble: 6 x 10  carat       cut color clarity depth table price     x     y     z  <dbl>     <ord> <ord>   <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl>1  0.23     Ideal     E     SI2  61.5    55   326  3.95  3.98  2.432  0.21   Premium     E     SI1  59.8    61   326  3.89  3.84  2.313  0.23      Good     E     VS1  56.9    65   327  4.05  4.07  2.314  0.29   Premium     I     VS2  62.4    58   334  4.20  4.23  2.635  0.31      Good     J     SI2  63.3    58   335  4.34  4.35  2.756  0.24 Very Good     J    VVS2  62.8    57   336  3.94  3.96  2.48
       使用length函数和 attr函数考察属性可以看到:

> attr(diamonds,"names") [1] "carat"   "cut"     "color"   "clarity" "depth"   "table"   "price"   [8] "x"       "y"       "z"      > length(diamonds$carat)[1] 53940
         为啥不用sttributes() 函数呢?因为太长了,会输出一个list,包含了三个部分,名字分别为$class,$row.names,$names三部分,这里不想列那么长了,占格子,是不是很有道理。

         最后注意,NULL表示空值,在做循环初始定义的时候很有用,NA是表示缺失,但是有时候往往不得不有这个值,理由大家都懂的

        

         最后呢,欢迎各位大佬前辈同人指点,虽然最后还是写偏了,但是没办法,这些东西我觉得比后面怎么产生向量,怎么运用向量可能更容易被遗忘,所以我就想先写写,哈哈哈

           

         

       

        

原创粉丝点击