美文网首页
【R】R语言基础-1.数据结构

【R】R语言基础-1.数据结构

作者: 我写的BUG代码少 | 来源:发表于2020-08-26 17:03 被阅读0次

    1. 数据结构

    1.1 向量

    • 向量:有序的数字列表
    • 操作函数:==c()==
    • 向量支持四则运算

    查看向量的长度

    length()  
    

    创建向量

    • 连续序列
    A <- c(1:3) #关键字c,向量1-3,赋值给A
    print(A)
    >>>
    1,2,3
    
    • 有步长序列
    #seq(from=,to=,by=)
    B <- seq(2,10,2)
    print(B)
    >>>
    2  4  6  8 10
    
    • 重复值序列
    #rep(value,frequency)
    C <- rep(0,5)
    >>>
    0 0 0 0 0
    
    x <- rep(c(1, 2, 3), 2)
    print(x)
    >>>
    1 2 3 1 2 3
    
    x <- rep(c(1, 2, 3), each = 2)
    print(x)
    >>>
    1 1 2 2 3 3
    

    向量的调用

    a[index]              #调用单个,index位置所在的向量
    a[c(index_1,index_2)] #调用多个
    a[index_1:index_2]    #index_1~index_2
    a[-index]             #调用除了index之外的向量
    

    修改向量

    插入数据

    • 默认在最后插入
    #Append(vector, new_value)
    A <- c(1,2,3)
    print(A)
    b <- append(A,4)
    print(b)
    >>> 1 2 3 4
    
    • 指定位置插入
    #append(vector, new_value, after = index)
    A <- c(1,2,3)
    print(A)
    b <- append(A,4,after=2)
    print(b)
    

    替换

    #replace(data,from=,to=)
    A <- c(1,2,3,4,5)
    A <- replace(A,1,8)
    print(A)
    >>>
    8 2 3 4 5
    
    '''
    replace(data)
    '''
    

    删除

    • 删除值
    A <- c(1,2,3,4,5)
    A <- A[-3]
    print(A)
    >>>
    1 2 4 5
    
    • 删除区间
    A <- c(1,2,3,4,5)
    A <- A[-c(3:4)]
    print(A)
    >>>
    1 2 5
    

    向量的运算

    • 支持加减乘除
    x <- c(1, 2, 3)
    y <- c(4, 5, 6)
    print(x + y)
    #x+y^2+2
    >>>
    5 7 9
    
    • 整除:x%/%y
    • 取余:x%%y
    • 转置
    t(x)
    

    向量中的缺失数据/无意义数据

    • 分类
      • NA: 缺失数据
      • NaN:无意义数据,如sqrt(-2),0/0
      • Inf:正无穷大
      • -Inf:负无穷大
    • 判断缺失/无意义数据
    vector <- c(1 / 0, 0 / 0, NA, -1 / 0)
    >>>
    Inf  NaN   NA -Inf
    
    #判断是否存在缺失/无意义数据
    is.na(vector) 
    >>>
    FALSE  TRUE  TRUE FALSE
    
    #判断无意义数据
    is.nan(vector)
    >>>
    FALSE  TRUE FALSE FALSE 
    
    • 转换成缺失值
    is.na(v) <- c(2,4)   #把2,4位置上的value转换成NA
    
    • 寻找/定位缺失值--返回index
    which(is.na(v))
    
    • 获取非缺失值的序列
    vector[!is.na(vector)]  #感叹号:逻辑值取反
    

    向量的拼接

    • 行拼接:rbind()
    • 列拼接:cbind()
    • 向量的拼接会强制将 numeric--->character
    x <- c("a", "b", "c")
    y <- c(1, 2, 3)
    rbind(x, y)
    >>>
      [,1] [,2] [,3]
    x "a"  "b"  "c"
    y "1"  "2"  "3"
    
    ***
    cbind(x, y)
    >>>
         x   y
    [1,] "a" "1"
    [2,] "b" "2"
    [3,] "c" "3"
    

    1.2 矩阵 matrix

    矩阵的创建

    matrix(range,nrow,ncol,byrow,dimnames=list(rnames,cnames))
    
    matrix(vector, nrow, ncol)
    
    #m1 <- matrix(1:15,nrow = 3,ncol = 5,byrow = T) # byrow:是否按行排列 T:按行排列
    m1 <- matrix(1:15,3,5,T)
    print(m1)
    >>>
         [,1] [,2] [,3] [,4] [,5]
    [1,]    1    2    3    4    5
    [2,]    6    7    8    9   10
    [3,]   11   12   13   14   15
    

    查看矩阵的维度

    dim()
    
    x <- matrix(1:15, 3, 5, T)
    print(dim(x))
    >>>
    3 5
    

    矩阵的调用

    x <- matrix(1:15, 3, 5, T)
    print(x)
    >>>
          [,1] [,2] [,3] [,4] [,5]
    [1,]    1    2    3    4    5
    [2,]    6    7    8    9   10
    [3,]   11   12   13   14   15
    
    ******
    #获取单个
    x[3,2]
    >>>12
    
    #获取区域
    x[1:3,2:4]
    >>>
          [,1] [,2] [,3]
    [1,]    2    3    4
    [2,]    7    8    9
    [3,]   12   13   14
    
    #跨行列获取
    x[c(1,3),c(2:4)] #,和: 都可以
    >>>
          [,1] [,2] [,3]
    [1,]    2    3    4
    [2,]   12   13   14
    

    矩阵的运算

    • 矩阵的乘法:x%*%y
    • 矩阵的加法:x+y
    # matrix + correction
    

    1.3 数组 Array

    arr <- array(1:15,c(2,5,3))
    print(arr)
    >>>
    '''
    , , 1
    
         [,1] [,2] [,3] [,4] [,5]
    [1,]    1    3    5    7    9
    [2,]    2    4    6    8   10
    
    , , 2
    
         [,1] [,2] [,3] [,4] [,5]
    [1,]   11   13   15    2    4
    [2,]   12   14    1    3    5
    
    , , 3
    
         [,1] [,2] [,3] [,4] [,5]
    [1,]    6    8   10   12   14
    [2,]    7    9   11   13   15
    '''
    

    1.4 列表 List

    列表的创建

    • 数据类型可以不一致
    lst <- list("Red", "Green", c(1, 15, 2), TRUE, 51.2)
    print(lst)
    >>>
    [[1]]
    [1] "Red"
    
    [[2]]
    [1] "Green"
    
    [[3]]
    [1]  1 15  2
    
    [[4]]
    [1] TRUE
    
    [[5]]
    [1] 51.2
    

    命名 named

    list(title='', col1_name= vector1 , col2_name = vector2)
    
    f <- c('apple','orange','banana')
    q <- c(1,2,6)
    mytitle <- 'lunch'
    list(title=mytitle,quantity=q,fruit=f)
    

    增加 add

    • 新增list
    lst[['new_col']] <- new_lst
    
    # 原lst
    f <- c('apple','orange','banana')
    q <- c(1,2,6)
    mytitle <- 'lunch'
    lst <- list(title=mytitle,quantity=q,fruit=f)
    
    # 新lst
    d <- list('coke','lemonade')
    
    # add
    lst[['drinks']] <- d
    

    删除 remove

    lst[['col_name']] <- NULL
    
    lst[['drinks']] <- NULL
    

    1.5 数据框 DataFrame/Dataset

    • 列名不能为空
    • row名要是unique
    • 可以存储任意类型的数据
    • attach(df)detach(df) 在environment中导入和解绑数据框

    创建 dataframe

    • 通过拼接函数生成df
    data.frame(rbind(x, y))
    >>>
      X1 X2 X3
    x  a  b  c
    y  1  2  3
    ***
    data.frame(cbind(x, y))
    >>>
      x y
    1 a 1
    2 b 2
    3 c 3
    
    • 通过data.frame()生成
    data.frame(col_1 = x, col_2 = y)
    >>>
      col_1 col_2
    1     a     1
    2     b     2
    3     c     3
    

    查看/获取/筛选

    查看df内的数据类型

    str(df)
    

    查看行/列名字

    d1 <- data.frame(col_1 = x, col_2 = y)
    names(d1)       #查看列名
    rownames(d1)    #查看行名
    >>>
    "col_1" "col_2"
    "1" "2" "3"
    

    查看行列数

    nrow() #行数
    ncol() #列数
    
    summarise(df, n()) # 获取行数/ records的条目数
    

    获取头/尾数据

    #默认查看前6行
    head(iris)  #iris 自带数据框
    
    #查看指定行数,10行
    head(iris, 10)
    
    #查看后几行
    tail()
    

    获取列数据

    #dataset[nrow,ncol]
    iris[,5]      #取第5列
    
    iris$Species  #数据框$列名
    

    剔除(丢弃)变量/ 列

    df[!col_name]
    df[!c(3:6)]
    

    按条件筛选: which()

    #取某列:  which(数据框$列名=="条件")
    which(iris$Species == "versicolor")
    
    #单条件筛选获取所有数据
    iris[which(iris$Species == "versicolor"), ] #取所有Species是versicolor的数据
    
    #多条件筛选: &(and); |(or)
    iris[which(iris$Species == "versicolor" & iris$Sepal.Width > 3), ]
    
    #获取某列值最大的数据 which.max(数据框$列)
    which.max(iris$Species)
    
    #获取某列值最小的数据 which.min(数据框$列)
    which.min(iris$Species)
    
    iris[which.max(iris$Sepal.Width), which(names(iris) == "Species")
    #叶宽最大的Species
    >>>
    setosa
    

    查看层次

    #levels(数据框$列)
    levels(iris$Species) 
    >>>
    "setosa"     "versicolor"  "virginica"
    

    获取子字符串

    • substr(x, start, stop)
    '''
    df = data.frame(col_1=c('hahha','heheh','xixiixi'), col_2=(1:3))
    >>>
    col_1  col_2
    hahha    1 
    heheh    2 
    xixiixi  3
    '''
    substr(df$col_1,1,3)
    >>>
    'hah' 'heh' 'xix'
    

    排序

    df[order(col1.col2),]
    
    leadership[order(gender, age),]  # 年龄升序排序
    leadership[order(gender, -age),] # 年龄降序排序
    

    修改

    ==修改列名==

    • 方法1:
    library(dplyr)
    
    rename(df, col_name = 'new_name')
    rename(df, c(oldname1="newname1", oldname2="newname2",...))
    
    • 方法2:
    df <- data.frame(col_1 = x, col_2 = y)
    names(df) <- c("new_1", "new_2") #修改
    print(df)
    >>>
      new_1 new_2
    1     a     1
    2     b     2
    3     c     3
    
    names(df[2]) = 'new_name'  # df第2列的名字重命名为new_name
    names(df[6:9]) = c('n6','n7','n8','n9')
    

    修改value

    variable[condition] <- expression
    
    leadership$age[leadership$age == 99] <- NA # 将99岁的年龄值重编码为缺失值
    leadership$agecat[leadership$age > 75] <- "Elder" # 创建agecat变量/ 创建新列并赋值
    
    leadership <- within(leadership,{ 
                                    agecat <- NA 
                                    agecat[age > 75] <- "Elder" 
                                    agecat[age >= 55 & age <= 75] <- "Middle Aged" 
                                     agecat[age < 55] <- "Young" })
    
    • car包/ recode()函数:重编码数值型、字符型向量或因子
    • doBy包/ recodevar()函数
    • R自带/ cut():,可将一个数值型变量按值域切割为多个区间,并返回一个因子

    行列转置

    t() #vector/df/df$col
    

    拼接

    • paste(dfcol_1, dfcol_2, sep='')
    paste(df$col_1, df$col_2, sep=',')
    >>> 
    'hahha,1' 'heheh,2' 'xixiixi,3'
    

    ==替换==

    • gsub()
    gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,fixed = FALSE, useBytes = FALSE)
    
    # remove comma
    gsub(',' , '', df)
    
    

    DF 缺失值

    判断缺失值

    any(is.na(df))   #只要有NA就返回True
    
    is.na(df)        # 所有位置上返回T/F
    is.na(df[,6:10]) # 将数据框限定到第6列至第10列
    

    寻找/定位缺失值

    apply(is.na(df), 1, which)  #1----按行统计显示
    apply(is.na(df), 2, which)  #2----按列统计显示
    

    获取非缺失值

    df[!is.na(df)]
    

    ==处理缺失值==

    方法1:用0值填充
    # m1:
    df[is.na(df)] <- 0
    
    # m2:
    library(imputeTS)
    df <- na_replace(df, 0)
    
    方法2:用均值填充
    mean_colname <- mean(df$colname, na.rm=T)  # na.rm==na.remove,是否在计算时移除缺失值
    new_colname <- ifelse(is.na(df$colname), mean_colname, df$colname)
    #用新的mean_colname,取代原df$colname
    
    df$col[is.na(df$col)] <- mean(df$col, na.rm =T)
    
    方法3:只要含缺失值,就移除当行
    na.omit(df)
    
    ==方法4:用预测数据填充== ==?????== Link
    # y = ax +b 
    # death = a*case + b
    # 因变量 ~ 自变量
    lm(y ~ x, data = na.omit(df))  # df[-c(1:5),]
    # lm(death ~ case, data = na.omit(df))  # death, case---col_name
    

    数据合并/ 表连接 merge()

    merge(dataframe1,dataframe2, by="col") #key = col
    
    library(tidyverse) 
    
    new_df= df_1 %>%
      left_join(df_2, by = "TheSameKey") %>%
      left_join(df_3, by = c("KeyIn_df_1" = "KeyIn_df_3"))  
    
    # 纵向合并(列名相同)
    rbind(df_1, df_2)c
    
    # 横向扩展(行数相同)
    cbind(df_1, df_2)
    

    1.6 因子 Factor

    • 名义型、有序型变量、连续性变量

      • 名义型变量是没有顺序之分的类别变量。eg. 糖尿病类型Diabetes(Type1、Type2)
      • 有序型变量表示一种顺序关系,而非数量关系。eg. 病情Status(poor、improved、excellent)是顺序型变量
      • 连续型变量可以呈现为某个范围内的任意值,并同时表示了顺序和数量。eg. 年龄Age就是一个连续型变量,它能够表示像14.5或22.8这样的值以及其间的其他任意值。
    • 内部关联逻辑 为1=Excellent、2=Improved、3=Poor (高--->低)

      • 可指定排序顺序

        factor(status, order=TRUE, 
         levels=c("Poor", "Improved", "Excellent"))
        
        # 1=Poor、2=Improved、3=Excellent
        
    • 数值型变量可以用levels和labels参数来编码成因子

      # 男性被编码成1,女性被编码成2
      factor(sex, levels=c(1, 2), labels=c("Male", "Female"))
      

    1.7 数据类型的判断及转换

    判断数据类型

    • 查找数据属性
    • class和mode的区别 Link
    class() #判断数据结构类型
    mode()  #判断数据类型
    '''
    (1)当x是单个值,或者向量的时候,
            返回的结果和mode一致,如numeric,character
    (2)其他情况(矩阵,数组,日期,因子),
            class返回(matrix,array,Date,factor)
            mode返回(x中元素的类型——在内存中的存储类型)
    (3)当x是数据框的时候
            class返回dataframe
            mode返回list
     (4)当x是列表的时候
            class和mode都返回list
            
    为何数据框和列表不再适用于第二条mode返回x中元素的类型了呢?
    1.因为数据框其实是列表的一种特殊情况
    2.list和dataframe中的数据类型可以不一致,所以没法返回一个类型代表多种元素类型
    '''
    
    • 判断数据类型
    is.numeric()        #是否数值型数据
    is.character()      #是否字符型数据  
    is.vector()         #是否向量数据
    is.matrix()         #是否矩阵数据
    is.data.frame()     #是否数据框数据
    is.factor()         #是否因子数据
    is.logical()        #是否逻辑型数据
    

    转换数据类型

    as.numeric()
    as.character()
    as.vector()
    as.matrix()
    as.data.frame()
    as.factor()
    as.logical()
    

    相关文章

      网友评论

          本文标题:【R】R语言基础-1.数据结构

          本文链接:https://www.haomeiwen.com/subject/kolfsktx.html