用R替換數據

儲存數據,尤其是字元型數據,有時候不會儲存完整的內容,可能會用一個字元代替整個內容,這樣會使存儲的體積更小,那麼我們在使用時候需要將數據完整的表達出來。下面是一個如何替換數據的例子。

我使用關於蘑菇種類的一個數據集。

install.packages("bitops")install.packages("RCurl")library("bitops")library("RCurl")# 輸入數據url = "https://raw.githubusercontent.com/chrisestevez/MSDA-Bridge/master/mushroom.csv"Rdata = getURL(url)MyData = read.csv(text = Rdata,header = FALSE,sep=",")MyFinalData = data.frame(MyData)samp = head(MyFinalData, n = 10)

以上我們完整的將數據導入到了內存中,為了方便展示,我截取前十個row作為例子

> samp V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V141 p x s n t p f c n k e e s s2 e x s y t a f c b k e c s s3 e b s w t l f c b n e c s s4 p x y w t p f c n n e e s s5 e x s g f n f w b k t e s s6 e x y y t a f c b n e c s s7 e b s w t a f c b g e c s s8 e b y w t l f c b n e c s s9 p x y w t p f c n p e e s s10 e b s y t a f c b g e c s s V15 V16 V17 V18 V19 V20 V21 V22 V231 w w p w o p k s u2 w w p w o p n n g3 w w p w o p n n m4 w w p w o p k s u5 w w p w o e n a g6 w w p w o p k n g7 w w p w o p k n m8 w w p w o p n s m9 w w p w o p k v g10 w w p w o p k s m

我們取其中的V1, V3,V5,V7 作為子集,並且替換每列的標籤

samp = subset(samp, select = c(V1,V3,V5,V9))colnames(samp) = c("MushroomType","CapSurface","Bruises","GillSize")

輸出如下:

> samp MushroomType CapSurface Bruises GillSize1 p s t n2 e s t b3 e s t b4 p y t n5 e s f b6 e y t b7 e s t b8 e y t b9 p y t n10 e s t b

下面我們要將其中每個cell的字母所代表的意思列出來,當然,如果用圖形表示的話並不需要全部替換,但是有時候需要將表格出示。

# 替換數據samp$MushroomType = c(p="poisonous",e="edible")[ as.character(samp$MushroomType)]samp$CapSurface = c(f="fibrous",g="grooves",y=scaly,s="smooth")[ as.character(samp$CapSurface)]samp$Bruises = c(t="bruises",f="no")[ as.character(samp$Bruises)]samp$GillSize = c(b="broad",n="narrow")[ as.character(samp$GillSize)]

最終輸出結果如下:

> samp MushroomType CapSurface Bruises GillSize1 poisonous smooth bruises narrow2 edible smooth bruises broad3 edible smooth bruises broad4 poisonous scaly bruises narrow5 edible smooth no broad6 edible scaly bruises broad7 edible smooth bruises broad8 edible scaly bruises broad9 poisonous scaly bruises narrow10 edible smooth bruises broad

---------------

作者:dykin

專欄:Dykins Blog

大家也可以加小編微信:tswenqu (備註:知乎),進R語言中文社區 交流群,可以跟各位老師互相交流

推薦閱讀:

數據分析師之必備Excel使用技巧1-6
實驗數據中是否可以捨去少數顯著不合理的部分?判據是怎樣的?
5萬多行數據用excel做地圖經常卡死,除了換電腦,還有什麼好的方法解決?
如何利用SAS使得程序更加標準化、自動化一些,減少人工操作,從而提高運行效率?

TAG:R编程语言 | 数据处理 |