R語(yǔ)言幾個(gè)解決方法總結(jié)

作為R語(yǔ)言新手,在使用R語(yǔ)言的過(guò)程中遇到了很多的問(wèn)題露氮。本文總結(jié)了幾個(gè)常見(jiàn)問(wèn)題的解決方法,希望對(duì)需要的人能有所幫助近哟。

R語(yǔ)言幾個(gè)解決方法總結(jié)

初學(xué)R語(yǔ)言會(huì)遇到很多問(wèn)題盐股,都是細(xì)細(xì)碎碎的小點(diǎn)钱豁,但是最困難的是,以前也沒(méi)有系統(tǒng)的學(xué)過(guò)Matlab疯汁,對(duì)于類似語(yǔ)言的使用尤其是在一些思想上一時(shí)半會(huì)轉(zhuǎn)變不過(guò)來(lái)牲尺。只好邊學(xué)邊用先積累了,這里把遇到的一些問(wèn)題總結(jié)一下記錄下來(lái)幌蚊。每個(gè)問(wèn)題都是獨(dú)立的谤碳,彼此之間沒(méi)有什么聯(lián)系。

sprintf調(diào)用C函數(shù)sprintf溢豆,可以用來(lái)格式化字符串

> sprintf("%04d", 1)
[1] "0001"
> sprintf("%04d", 104)
[1] "0104"
> sprintf("%010d", 104)
[1] "0000000104"

安裝data.table

data.table是個(gè)好用的包蜒简,安裝方法可以參考這里:https://class.coursera.org/getdata-008/forum/thread?thread_id=58

Here is how I installed the data.table package:

Used my browser to download data.table_1.9.4.zip from page http://cran.r-project.org/web/packages/data.table/index.html

Put the downloaded file in my R working directory.

> install.packages("data.table_1.9.4.zip", repos=NULL)
> install.packages("plyr")
> install.packages("Rcpp")
> install.packages("rshape2")
> install.packages("chron")

Once done with that, I could do:
> library(data.table)
and everything else worked.

order的用法

對(duì)一個(gè)vector或者data.frame排序可以使用order函數(shù),關(guān)于order和rank函數(shù)的使用和結(jié)果解釋需要注意:

You can use the order() function directly without resorting to add-on tools -- see this simpler answer which uses a trick right from the top of the example(order) code:
R> dd[with(dd, order(-z, b)), ]
    b x y z
4 Low C 9 22 Med D 3 11  Hi A 8 13  Hi A 9 1
Edit some 2+ years later: It was just asked how to do this by column index. The answer is to simply pass the desired sorting column(s) to the order() function:
R> dd[ order(-dd[,4], dd[,1]), ]
    b x y z
4 Low C 9 22 Med D 3 11  Hi A 8 13  Hi A 9 1
R> 
rather than using the name of the column (and with() for easier/more direct access).

關(guān)于order函數(shù)結(jié)果的解釋:

The definition of order is that a[order(a)] is in increasing order. This works with your example, where the correct order is the fourth, second, first, then third element.
You may have been looking for rank, which returns the rank of the elements
R> a <- c(4.1, 3.2, 6.1, 3.1)
R> order(a)
[1] 4 2 1 3
R> rank(a)
[1] 3 2 4 1
so rank tells you what order the numbers are in, order tells you how to get them in ascending order.
plot(a, rank(a)/length(a)) will give a graph of the CDF. To see why order is useful, though, try plot(a, rank(a)/length(a),type="S") which gives a mess, because the data are not in increasing order
If you did
oo<-order(a)
plot(a[oo],rank(a[oo])/length(a),type="S")
or simply
oo<-order(a)
plot(a[oo],(1:length(a))/length(a)),type="S")
you get a line graph of the CDF.

判斷vector中是否有某一個(gè)元素

v <- c('a','b','c','e')
'b' %in% v
## returns TRUE

match('b',v)
## returns the first location of 'b', in this case: 2

> x <- sample(1:10)
> x
 [1]  4  5  9  3  8  1  6 10  7  2
> match(c(4,8),x)
 [1] 1 5
match only returns the first encounter of a match, as you requested.
For multiple matching, %in% is the way to go :
> x <- sample(1:4,10,replace=T)
> x
 [1] 3 4 3 3 2 3 1 1 2 2
> which(x %in% c(2,4))[1]  2  5  9 10

關(guān)于給vector中添加元素

Here are several ways to do it. All of them are discouraged. Appending to an object in a for loop causes the entire object to be copied on every iteration, which causes a lot of people to say "R is slow", or "R loops should be avoided".

# one way
for (i in 1:length(values))
  vector[i] <- values[i]

# another way
for (i in 1:length(values))
  vector <- c(vector, values[i])

# yet another way?!?
for (v in values)
  vector <- c(vector, v)
# ... more ways

help("append") would have answered your question and saved the time it took you to write this question (but would have caused you to develop bad habits). ;-)

Note that vector <- c() isn't an empty vector; it's NULL. If you want an empty character vector, use vector <- character().

Also note, as BrodieG pointed out in the comments: if you absolutely must use a for loop, then at least pre-allocate the entire vector before the loop. This will be much faster than appending for larger vectors.

set.seed(21)
values <- sample(letters, 1e4, TRUE)
vector <- character(0)# slow
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#  user  system elapsed
#  0.340  0.000  0.343
vector <- character(length(values))# fast(er)
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#  user  system elapsed 
#  0.024  0.000  0.023

要注意的是漩仙,這里有性能方面的問(wèn)題臭蚁。

刪除data.frame中的一列

> head(data)
   chr       genome region
1 chr1 hg19_refGene    CDS
2 chr1 hg19_refGene   exon
3 chr1 hg19_refGene    CDS
4 chr1 hg19_refGene   exon
5 chr1 hg19_refGene    CDS
6 chr1 hg19_refGene   exon



You can set it to NULL.
> Data$genome <- NULL
> head(Data)
   chr region
1 chr1    CDS
2 chr1   exon
3 chr1    CDS
4 chr1   exon
5 chr1    CDS
6 chr1   exon

As pointed out in the comments, here are some other possibilities:
Data[2] <- NULL    # Wojciech Sobala
Data[[2]] <- NULL  # same as above
Data <- Data[,-2]  # Ian Fellows
Data <- Data[-2]   # same as above

You can remove multiple columns via:    
Data[1:2] <- list(NULL)  # Marek
Data[1:2] <- NULL        # does not work!

Be careful with matrix-subsetting though, as you can end up with a vector:    
Data <- Data[,-(2:3)]             # vector
Data <- Data[,-(2:3),drop=FALSE]  # still a data.frame

從字符串中去除括號(hào)

string <- "log(M)"
gsub("log", "", string) # Works just fine
gsub("log(", "", string) #breaks
# Error in gsub("log(", "", test) : 
#   invalid regular expression 'log(', reason 'Missing ')''

Escape the parenthesis with a double-backslash:
要用雙斜線來(lái)轉(zhuǎn)義括號(hào)
gsub("log\\(", "", string)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市讯赏,隨后出現(xiàn)的幾起案子垮兑,更是在濱河造成了極大的恐慌,老刑警劉巖漱挎,帶你破解...
    沈念sama閱讀 218,858評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件系枪,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡磕谅,警方通過(guò)查閱死者的電腦和手機(jī)私爷,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)膊夹,“玉大人衬浑,你說(shuō)我怎么就攤上這事》排伲” “怎么了工秩?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,282評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)进统。 經(jīng)常有香客問(wèn)我助币,道長(zhǎng),這世上最難降的妖魔是什么螟碎? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,842評(píng)論 1 295
  • 正文 為了忘掉前任眉菱,我火速辦了婚禮,結(jié)果婚禮上掉分,老公的妹妹穿的比我還像新娘俭缓。我一直安慰自己克伊,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布华坦。 她就那樣靜靜地躺著愿吹,像睡著了一般。 火紅的嫁衣襯著肌膚如雪季春。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,679評(píng)論 1 305
  • 那天消返,我揣著相機(jī)與錄音载弄,去河邊找鬼。 笑死撵颊,一個(gè)胖子當(dāng)著我的面吹牛宇攻,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播倡勇,決...
    沈念sama閱讀 40,406評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼逞刷,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了妻熊?” 一聲冷哼從身側(cè)響起夸浅,我...
    開(kāi)封第一講書(shū)人閱讀 39,311評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎扔役,沒(méi)想到半個(gè)月后帆喇,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,767評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡亿胸,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年坯钦,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片侈玄。...
    茶點(diǎn)故事閱讀 40,090評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡婉刀,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出序仙,到底是詐尸還是另有隱情突颊,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評(píng)論 5 346
  • 正文 年R本政府宣布潘悼,位于F島的核電站洋丐,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏挥等。R本人自食惡果不足惜友绝,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望肝劲。 院中可真熱鬧迁客,春花似錦郭宝、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,988評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至卜范,卻和暖如春衔统,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背海雪。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,101評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工锦爵, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人奥裸。 一個(gè)月前我還...
    沈念sama閱讀 48,298評(píng)論 3 372
  • 正文 我出身青樓险掀,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親湾宙。 傳聞我的和親對(duì)象是個(gè)殘疾皇子樟氢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容