《R语言实战》自学笔记5-数据框

Python012

《R语言实战》自学笔记5-数据框,第1张

数据框(data.frame)是R中最常处理的数据结构。

函数:data.frame(col1,col2,col3,....,row.name=NULL, check.rows = FALSE, check.names=TRUE, stringsAsFactors = default.stringsAsFactors())

其中的列向量col1, col2, col3,...可为任何类型(如字符型、数值型或逻辑型),每一列的名称可由函数names指定;

row.name用于指定各行(样本)的名称,默认没有名称,使用从1开始自增的序列来标识每一行;

check.rows用于用来检查行的名称和数量是否一致,默认为FALSE;

check.names来检查变量(列)的名称是否唯一且符合语法,默认为TRUE;

stringsAsFactors用来描述是否将字符型向量自动转换为因子,默认转换,若不改变的话使用stringsAsFactors = FALSE来指定即可。

每一列数据的模式必须唯一,不过你却可以将多个模式的不同列放到一起组成数据框。

先构建向量,再组成数据框。

直接用data.frame函数构建数据框。

R语言的下标索引是从1开始的,且下标索引为负数的话表示删除某个元素。

[] 可进行索引,括号内对应的是[行下标, 列下标]。

[1] 1 2 3 4 5 6 7 8

[1] "four"

[1] 1 2 3 4 5 6 7 8

[1] "four"

[1] 1 2 3 4 5 6 7 8

[1] "one" "two" "three"

attach、detach和with()

函数attach()可将数据框添加到R的搜索路径中。

函数detach()将数据框从搜索路径中移除。

函数attach()和detach()最好在你分析一个单独的数据框,并且不太可能有多个同名对象时使用。

with()就是把所有操作都限制在数据框上。

The following objects are masked by .GlobalEnv:

[1] 1 2 3 4 5 6 7 8

[1] "n1" "n2" "n3" "n4" "n5" "n6" "n7" "n8"

[1] 8

[1] 3

[1] 8

[1] "name""values" "values2"

[1] "r1" "r2" "r3" "r4" "r5" "r6" "r7" "r8"

[1] 8 3

[1] "data.frame"

[1] "numeric"

[1] "character"

Length:8 Min. :1.00 Min. :1.00

Class :character 1st Qu.:2.75 1st Qu.:2.75

Mode :character Median :4.50 Median :4.50

Mean :4.50 Mean :4.50

3rd Qu.:6.25 3rd Qu.:6.25

Max. :8.00 Max. :8.00

[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

R语言-v1-基础知识

Iretara  12-17 21:18

以例题的形式简述R语言基础知识

# 读取文件

setwd(" 文件链接的时候,用  /  ")

install.packages(" readxl ")

library(readxl)

library (tidyverse)

hw1_a<- read_excel ("hw1_a.xlsx", col_types=c("numeric", "numeric", "numeric", "numeric", "numeric") )

hw1_b<- read_excel ("hw1_b.xlsx")

#读取csv

library(readr)

hw1_a<- read_csv ("/")

View(hw1_a)

# 描述型函数

hw1_a + hw1_b 表

#描述最小值,最大值,中值,均值,标准差

Str (hw1_a) #查看数据并指出各个 变量的形式

summary (hw1_a) #指出各个变量的形式, 最小值,最大值,中值,均值

library(psych)

describe (hw1_a) #比summary更简便的方法, 可以直接读取标准差等;但是,使用describe不可读取 NA值, 可以尝试使用 Hmisc包中 describe

描述型函数-R

# 连接

hw1_a %>% inner_join (hw1_b, by ="ID")

hw1_a %>% left_join (hw1_b, by ="ID")

hw1_a %>% right_join (hw1_b, by ="ID")

hw1_a %>% full_join (hw1_b, by ="ID")

inner_join<- inner_join (hw1_a,hw1_b, by =“ID”) #报告合并后的 总行数 ,178行

full_join<- full_join (hw1_a,hw1_b, by ="ID")

( nrow (full_join)) #报告合并后的 总行数 ,200行

>  length (full_join$ID)

#找出各个列的 缺失值

i<-NA

a<-NA

for(i in 1:length(full_join[1,])){ a[i]<- sum(is.na( full_join[,i] ) ) }

paste("缺失值是",a)

#缺失值总数

sum(is.na(full_join))

#删除缺失值 na.omit()

full_join1=filter(full_join,!is.na(full_join[2]))

full_join1=filter(full_join1,!is.na(full_join1[3]))

full_join1=filter(full_join1,!is.na(full_join1[4]))

full_join1=filter(full_join1,!is.na(full_join1[5]))

full_join1=filter(full_join1,!is.na(full_join1[6]))

full_join1=filter(full_join1,!is.na(full_join1[7]))

full_join1=filter(full_join1,!is.na(full_join1[8]))

sum(is.na(full_join1))

找出Income中的 极端值 并滤掉对应行的数据

quantile (hw1_a$Income,c(0.025,0.975))

hw1_a2= filter (hw1_a,Income>14168.81 &Income<173030.92)

#使用dplyr进行数据转换

arrange()

>arrange (hw1_a,Income) #默认升序

>arrange(hw1_a, desc (Income)) #desc降序,NA排序一般最后

select()

>select (hw1_a, - (Years_at_Address:Income)) #不要变量

>rename (hw1_a, In_come=Income) #改名

>select(hw1_a,Income, exerything ()) #把Income放在前面

拓例题1:

library(nycflights13)

view(flights)

#counts

(1)

not_cancelled <- flights %>%

filter(! is.na(dep_delay), !is.na(arr_delay))

(2)

not_cancelled %>%

group_by (year,month,day) %>%

summarize (mean=mean(dep_delay))

(3)

delays <- not_cancelled %>%

group_by (tailnum) %>%

summarize (delay=mean(arr_delay))

ggplot (data=delays,mapping=aes(x= delay))+

geom_freqpoly (binwidth=10) #freqpoly

(4)

delays <- not_cancelled %>%

group_by(tailnum) %>%

summarize(delay=mean(arr_delay,na.rm=TRUE), n=n() ) #tailnum的次数

ggplot(data=delays,mapping=aes(x= n, y=delay))+

geom_point(alpha=1/10)

拓例题2:

#请按照价格的均值,产生新的变量price_new, 低于均值为“低价格”,高于均值为“高价格”。 同样对市场份额也是,产生变量marketshare_new, 数值为“低市场份额”和“高市场份额”

price=data1$price

pricebar=mean(price)

price_new= ifelse (price>pricebar,“高价格”,”低价格”)

marketshare=data1$marketshare

marketsharebar=mean(marketshare)

marketshare_new=ifelse(marketshare>marketsharebar ,“高市场份额”,”低市场份额”)

data1= mutate (data1,price_new,marketshare_new)

#可视化

#将Income 对数化

lninc<- log (hw1_a$Income)

#画出直方图和 density curve密度曲线

hist (lninc,prob=T)

lines ( density (lninc),col="blue")

# 添加额外变量 的办法,在 aes()中添加 样式 (color、size、alpha、shape)

ggplot(data=inner_join)+

geom_point(mapping = aes(x=Years_at_Employer,y= Income, alpha= Is_Default))

# 按照Is_Default 增加一个维度,使用明暗程度作为区分方式

ggplot(data=inner_join)+

geom_point(mapping = aes(x=Years_at_Employer,y= Income,

alpha=factor( Is_Default ) ))

#使用形状作为另外一种区分方式

ggplot(data=inner_join)+

geom_point(mapping = aes(x=Years_at_Employer,y= Income,

shape=factor( Is_Default)))

可视化-R

拓展:

#将 flight1 表和 weather1 表根据共同变量进行内连接,随机抽取 100000 行数据, 将生产的结果保存为 flight_weather。 (提示:sample_n()函数,不用重复抽取)

flight_weather <- inner_join(flight1, weather1) %>% sample_n(100000)

# 从 flight_weather表中对三个出发机场按照平均出发延误时间排降序,并将结果保留在 longest_delay表中。把结果展示出来

longest_delay<- flight_weather %>%

group_by(origin) %>%

summarize(delay=mean(dep_delay, na.rm=TRUE )) %>%

arrange(desc(delay))

#根据不同出发地(origin)在平行的 3 个图中画出风速 wind_speed(x 轴)和出发 延误时间 dep_delay(y 轴)的散点图。

ggplot(data= flight_weather) +

geom_point(mapping=aes(x=wind_speed,y=dep_delay))+

facet_grid(.~origin, nrow = 3 ) # 按照class分类,分成3行

#根据 flight_weather 表,画出每个月航班数的直方分布图,x 轴为月份,y 轴是每个 月份航班数所占的比例。

ggplot(data=flight_weather)+

geom_bar(mapping=aes(x=month, y=..prop .., group=1))

#根据 flight_weather 表,画出每个月航班距离的 boxplot 图,x 轴为月份,y 轴为 航行距离, 根据的航行距离的中位数从低到高对 x 轴的月份进行重新排序

ggplot(data=flight_weather)+

geom_boxplot(mapping=aes(x= reorder (month,distance,FUN=median),y=distance))

线性回归

# 以Income作为因变量,Years at Employer作为自变量,进行 OLS回归

m1<- lm (Income ~ Years_at_Employer,data=hw1_a)

#通过***判断显著性

summary (m1)

#画出拟合直线

ggplot(data= hw1_a)+

geom_point(aes(x=Income,y=Years_at_Employer))+

geom_abline(data= m1,col= "blue")

#证明拟合直线是最优的

b0=runif(20000,-5,5)

b1=runif(20000,-5,5)

d<-NA

sum<-NA

n<-1

while(n<=20000){

for(i in 1:24){

d[i]<-(hw1_a $ Income[i]-b0[n]-b1[n]*hw2$ Years_at_Employer[i])^2}

sum[n]<-sum(d)

n<-n+1

}

resi=m1$residuals

resi2=sum(resi^2)

check=sum(as.numeric(sum<resi2))

check