天天看點

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" 的兩列删除掉

繼續閱讀