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"))
names(tianmao)

導入 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" 的兩列刪除掉

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章