R语言几个解决方法总结

作为R语言新手,在使用R语言的过程中遇到了很多的问题。本文总结了几个常见问题的解决方法,希望对需要的人能有所帮助。

R语言几个解决方法总结

初学R语言会遇到很多问题,都是细细碎碎的小点,但是最困难的是,以前也没有系统的学过Matlab,对于类似语言的使用尤其是在一些思想上一时半会转变不过来。只好边学边用先积累了,这里把遇到的一些问题总结一下记录下来。每个问题都是独立的,彼此之间没有什么联系。

sprintf调用C函数sprintf,可以用来格式化字符串

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

安装data.table

data.table是个好用的包,安装方法可以参考这里: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的用法

对一个vector或者data.frame排序可以使用order函数,关于order和rank函数的使用和结果解释需要注意:

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).

关于order函数结果的解释:

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中是否有某一个元素

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

关于给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

要注意的是,这里有性能方面的问题。

删除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

从字符串中去除括号

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:
要用双斜线来转义括号
gsub("log\\(", "", string)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,378评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,356评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,702评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,259评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,263评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,036评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,349评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,979评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,469评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,938评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,059评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,703评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,257评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,262评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,485评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,501评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,792评论 2 345

推荐阅读更多精彩内容