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

2020-08-26  本文已影响0人  我写的BUG代码少

1. 数据结构

1.1 向量

查看向量的长度

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
t(x)

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

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
which(is.na(v))
vector[!is.na(vector)]  #感叹号:逻辑值取反

向量的拼接

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

矩阵的运算

# 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

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

创建 dataframe

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(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"

获取子字符串

'''
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),] # 年龄降序排序

修改

==修改列名==

library(dplyr)

rename(df, col_name = 'new_name')
rename(df, c(oldname1="newname1", oldname2="newname2",...))
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" })

行列转置

t() #vector/df/df$col

拼接

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

==替换==

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

1.7 数据类型的判断及转换

判断数据类型

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()
上一篇下一篇

猜你喜欢

热点阅读