天天看点

R数据框操作 fourth day

#导入数据集

install.packages("readxl")

library(readxl)

tianmao<-read_excel('tianmaoTV.xlsx',skip =1 )

#创建新变量

tianmao['total_sales']<-tianmao$current_price*tianmao$month_sales_count

tianmao[c('current_price','month_sales_count','total_sales')]

tianmao

tianmao$zhekou<-tianmao$current_price/tianmao$original_price

tianmao$zhekou

#条件判断

a<-1:10

ifelse(a%%2==0,'偶数','奇数')

#对价格分类

tianmao['price_class']<-ifelse(tianmao$current_price<1000,'低价',

ifelse(tianmao$current_price<=2000,'适中','高价'))

tianmao[c('price_class','current_price')]#创建新变量 对之前的变量直接操作 第二章对变量进行判

#重命名

names(tianmao)#返回列名

names(tianmao)[1]<-'mingcheng' #修改第一列

View(tianmao)#视图

#不知道列在第几个

%in% #判断前一个向量的元素是否在后面的向量中

names(tianmao)[1]<-'mingcheng'

names(tianmao)%in%"weight"

names(tianmao)[names(tianmao)%in%"weight"]<-'zhongliang'

names(tianmao)#变量重名名

#从数据集中提取子集

newdata<-tianmao[,-c(1:3)]

newdata

names(newdata)

names(tianmao)

剔除数据集

col1<-c('mingcheng','description','current_price')

logical<-names(tianmao)%in%col1

#当作索引删除子集

newdata1<-tianmao[,!logical]

View(newdata1)

#对行进行操作

tianmao[1,] #第一行

logical1<-tianmao$brand=='Xiaomi/小米'

#提取观测

xiaomi<-tianmao[logical1,]

View(xiaomi)

logical1

#提取子集的方法

?subset

xiaomi1<-subset(tianmao,brand=='Xiaomi/小米',c("mingcheng","description"))

导入 tianmaoTV.xlsx,并把数据集命名成 tianmao_2,以下操作都基于 tianmao_2 数

据集

提取当前价格(current_price)小于 1000 的所有观测

在数据集 tianmao_2 中生成一个新列,将新列命名为 stock_class。

当库存(stock)等于 0,stock_class 的值为'无货';

库存(stock)小于 100,stock_class 的值为'低库存';

库存(stock)大于等于 100,stock_class 的值为'高库存'

提取 tianmao_2 的 stock、stock_class 两列

将列名为"shop_id","shop_name" 的两列删除掉

继续阅读