-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathR_tricks.R
2125 lines (1671 loc) · 73.3 KB
/
R_tricks.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# write tests in inst/tests dev_tools
test("/Users/nacho/Documents/Code/Rprojects/clickme")
test("/Users/nacho/Documents/Code/Rprojects/df2json")
auto_test("/Users/nacho/Documents/Code/Rprojects/clickme/R","/Users/nacho/Documents/Code/Rprojects/clickme/inst/tests")
dev_mode() # toggles
install("/Users/nacho/Documents/Code/Rprojects/clickme")
library("clickme")
# convert a nested list of lists to into a data frame
my_list <- list(list(a = 3,b = 2),list(a = 5,b = 3))
a <- ldply(my_list, data.frame) # works
a <- data.frame(do.call(rbind, my_list)) # doesn't really work, class(a$b) == "list"
# a b
# 3 2
# 5 3
# not in dev mode
library("clickme")
# loads code, data, etc. (in non-global env)
load_all("/Users/nacho/Documents/Code/Rprojects/clickme")
load_all("/Users/nacho/Documents/Code/Rprojects/clickme", T) # to force a true reload
test("/Users/nacho/Documents/Code/Rprojects/clickme") # load_all + test_dir("inst/tests")
document("/Users/nacho/Documents/Code/Rprojects/clickme") # run roxygen
check("/Users/nacho/Documents/Code/Rprojects/clickme")
check("/Users/nacho/Documents/Code/Rprojects/df2json")
# R errors
# argument is of length zero
if(NULL)
# object of type 'closure' is not subsettable
you’re using a list object that doesn’t exist
# remove file extension
strsplit(filename, "\\.")[[1]][1]
# get the file extension
strsplit(filename, "\\.")[[1]][2]
# get user input
response <- readline()
if (tolower(response) == "c"){
}
# use rsq instead of correlation squared
# http://www.win-vector.com/blog/2013/02/dont-use-correlation-to-track-prediction-performance/?utm_source = rss&utm_medium = rss&utm_campaign = dont-use-correlation-to-track-prediction-performance
rsq = function(y,f) { 1 - sum((y-f)^2)/sum((y-mean(y))^2) }
y = runif(10)
x = y + 0.5*runif(10)
cor(x,y) # 0.8893743
cor(y,x) # 0.8893743
cor(10*x,y) # 0.8893743
cor(x+10,y) # 0.8893743
rsq(x,y) # -0.4966555
rsq(y,x) # 0.09424879
rsq(10*x,y) # -9.197255
rsq(x+10,y) # -2250.407
# Rook http server
s$stop()
library(Rook)
load_all("/Users/nacho/Documents/Code/Rprojects/clickme")
s <- start_server("/Users/nacho/Documents/Code/Rprojects/clickme/inst/demo/data_nachocab_scatterplot.html")
# test that
expect_true(x)
expect_false(x)
expect_is(expected, x)
expect_equal(expected, x)
expect_equivalent(expected, x)
expect_identical(expected, x)
expect_matches(expected, x)
expect_output(expected, x)
expect_message(expected, x)
expect_warning(expected, x)
expect_error(expected, x)
# file utilities
file.create(..., showWarnings = TRUE)
file.exists(...)
file.remove(...)
unlink("file")
unlink("dir", recursive = TRUE)
file.rename(from, to)
file.append(file1, file2)
file.copy(from, to, overwrite = recursive, recursive = FALSE,
copy.mode = TRUE)
file.symlink(from, to)
file.link(from, to)
basename(path)
dirname(path)
dir.create(path, showWarnings = TRUE, recursive = FALSE, mode = "0777")
Sys.chmod(paths, mode = "0777", use_umask = TRUE)
Sys.umask(mode = NA)
system.file(..., package = "base", lib.loc = NULL, mustWork = FALSE)
tempfile(pattern = "file", tmpdir = tempdir(), fileext = "")
tempdir()
file.path(...) # construct the path in a platform-indep way
path.expand(path) # expand leading tilde
# hooks
hook_output = knit_hooks$get('output')
knit_hooks$set(output = function(x, options) { head(x, options$out.lines)} # all chunks call the output chunk
opts_chunk$set(out.lines = 4) # globally
```{r , out.lines = 4} # or by chunk
knit_hooks$set(foo1 = function(before, options, envir) {
if (before) {
"_I appear before a chunk!_\n\n"
} else {
"\n\n_I am after a chunk..._"
}
})
knit_hooks$set(chunk = function(x, options) {
gsub('```\n+```', '', x)
})
knit_hooks$set(source = function(x, options) {
paste0('\n\n```r\n', gsub('\\n', '\n', x, fixed = TRUE), '```\n\n')
})
# read r code and insert it into knitr
read_chunk(lines = demo.sub, labels = 'rgl-sub') # demo.sub has r code, we assign it the label 'rgl-sub'
```{r rgl-sub} # run the code
```
# get the column numbers of a dataframe
data.frame(colnames(df))
# pass by reference list
zz <- new.env()
zz$foo <- c(1,2,3,4,5)
make_six <- function(blah) {
foo <- 6
}
make_six(zz)
zz$foo # 6
# run a chunk inside another one
```{r a}
a <- 3
run_chunk('b') # don't use this, yihui changed it to ref.label and <<label>>
a
```
```{r b}
a <- 4
```
# get an object with a given name
a <- 3
get("a") # 3
eval(parse(text="a")) # 3
# local creates a new environment (perfect for counters)
fn = local({
i = 0
function(x) {
i <<- i + 1 # modify external variable
paste('Figure ', i, ': ', x, sep = '')
}
})
# barplot
# set names to an array
setNames( 1:3, c("foo", "bar", "baz")) # instead of tmp <- 1:3;names(tmp) <- c("foo", "bar", "baz");tmp
# To load R without the .rprofile
R -- vanilla
# divide a matrix by a vector (each column by its vector element)
a <- matrix(c(10,20,30,40,50,60), byrow = T, nrow = 2)
t(t(a)/c(5,7,3))
# 2 2.85714 10
# 8 7.14286 20
# ensure arguments are valid
a <-function(x, y = c("A","B")){ y <- match.arg(y); y}
a() # "A"
a(3,"A") # A
a(3,"C") # Error in match.arg(y) : 'arg' should be one of “A”, “B”
formals(a) # $x $y c("A","B")
# prepare a file for leanback
write_expression_d3(df, name="whatever", type="expression")
write_expression_d3(df, name="whatever", type="volcano")
# http://kaya1.bu.edu/leanback/expression/?file=../data/rescued_genes_lassa_flu_expression.csv&clusters = 1&groups = 1
# http://kaya1.bu.edu/leanback/volcano/?file=../data/rescued_genes_lassa_flu_volcano.csv&clusters = 1&groups = 1
# convert character to date
as.Date("5-oct-12", "%d-%b-%y") #"2012-10-05"
# %d Day of the month (decimal number)
# %m Month (decimal number)
# %b Month (abbreviated)
# %B Month (full name)
# %y Year (2 digit)
# %Y Year (4 digit)
# change locale
Sys.setlocale("LC_TIME", "es_ES")
# sanitize a string, clean, strip
make.names("-.!#paco$2") # "X....paco.2"
# make names unique
make.names(c("a","a","b"), unique = T) # "a" "a.1" "b"
# horizontal axis labels => 0 = parallel, 1 = all horizontal, 2 = all perpendicular to axis, 3 = all vertical
plot(...,las = 1)
# plot a regression line
plot(dge$norm_counts["ENSG00000075624",])
m_actb <- lm(y~x, data = data.frame(x = 1:4, y = dge$norm_counts["ENSG00000075624",]))
lines(m_actb$fit)
# remove the last two elements of a string by regex pattern
sub('(_[^_]+){2}$','','AA_BB_C-C_DD') # AA_BB
sub('(_[^_]+){2}$','',c('AA_BB_C-C_DD','AAA_BB_C') # AA_BB AAA
# color
palette() # "black" "red" "green3" "blue" "cyan" "magenta" "yellow" "gray"
colors() # white... yellowgreen (657)
palette( rev(rich.colors(32)) ) # rich rainbow
# cummulative sum: 1 ; 2 + 1 = 3; 3+3 = 6; 6+4 = 10
cumsum(1:4) # 1 3 6 10
cumsum(1:10) # 1 3 6 10 15 21 28 36 45 55
# lagged difference: substract the first and the lag+1
diff(c(0,10,4,17), lag = 1) # 10 -6 13; 10-0 = 10; 4-10=-6, basically, what is the change between two consecutive positions.
diff(c(0,10,4,17), lag = 2) # 4 7, 4-0 = 4; 17-10 = 7q
# set rownames and colnames at same time
dimnames(correlation) <- list(colors,colors)
# global variable constant
global_var <<- 3
assign("global_var", 3, envir = .GlobalEnv)
# scale: centers or scales
scale(x, center = TRUE, scale = TRUE) # default, substract column means and divide by the sd of each column, standardize the data
scale(x, center = c(3,4,5), scale = TRUE) # substract center array from every column
scale(x, center = TRUE, scale = c(3,4,5)) # divide the centered columns by scale
# plyr genius
library(plyr)
unrowname(df) # remove row names
arrange(df, column1) # sort by column(s)
arrange(df, column1, column2)
arrange(df, column1, desc(column2))
count(df, "column1") # count unique values
count(df, "column1", "column2") # count unique values
mutate(df, double = 2 * value) # add a column to a df that is a transformation of an existing column df$double <- 2 * df$value
summarise(df, double = 2 * value) # summarize a df
# interesting parts of a ggplot variable (p)
data
layers # geom_line, mapping, pointrange, position
scales # continuous, discrete
mapping
theme
coordinates # transformer
facet # facet_wrap(virus)
plot_env
labels # x,y,group, yintercept, ymin, ymax
# modify an existing column
# h(airquality)
# Ozone Solar.R Wind Temp Month Day
# 1 41 190 7.4 67 5 1
# 2 36 118 8.0 72 5 2
transform(airquality, new = -Ozone, Temp = (Temp-32)/1.8)
# h(transform(airquality, new = -Ozone, Temp = (Temp-32)/1.8))
# Ozone Solar.R Wind Temp Month Day new
# 1 41 190 7.4 19.4444 5 1 -41
# 2 36 118 8.0 22.2222 5 2 -36
# ddply: split-apply-combine
library(plyr)
ddply(input, split, fun_to_apply)
ddply(data, .(gene, timepoints, virus), function(x) data.frame(m_values = mean(x$m_values), sd = sd(x$m_values), se = se(x$m_values), ymin = mean(x$m_values)-sd(x$m_values), ymax = mean(x$m_values)+sd(x$m_values)) )
# add left line to plot before making horizontal y-labels
par(mar = par("mar")+c(0,1,0,0))
plot(...,las = 1)
# horizontal y-labels in ggplot (right-aligned)
ylab("log2\n\nfold\n\nincrease\n\nover\n\nuniversal\n\nreference") +
theme(..., axis.title.y = element_text(size = 15, angle = 0, hjust = 1, face="bold"))
# googleVis
```{r, results="asis"}
df <- data.frame(x = 1:10, y = 1:10)
suppressPackageStartupMessages(library(googleVis))
sc <- gvisScatterChart(data = df, options = list(width = 300, height = 300, legend='none', hAxis="{title:'x'}", vAxis="{title:'y'}"))
print(sc, 'chart') ## same as cat(sc$html$chart)
```
# ggplot horizontal vertical line
geom_hline(yintercept = 0, linetype="dotted", color="grey80", size = 1)
# knitr Rmd
```{r chunk_label, OPTIONS}
# R code
```
# create markdown table from R dataframe
```{r createtable, results='asis', echo = FALSE}
cat("x | y", "--- | ---", sep="\n")
cat(apply(df, 1, function(X) paste(X, collapse=" | ")), sep = "\n")
```
# global knitr options
opts_chunk$set(fig.width = 5, fig.height = 5)
opts_chunk$set(cache = TRUE, autodep = TRUE)
# CHUNK OPTIONS knitr
{..., eval = TRUE} # whether to evaluate the code chunk, it can also be numeric vector selecting which expression inside the chunk is executed c(1,3,4) or -(4:5)
{..., echo = FALSE} # hide code, it can also be numeric vector selecting which expression inside the chunk is executed c(1,3,4) or -(4:5)
{..., results='asis'} # output as text (instead of as console output), also "markup" (Sweave verbatim), "hide"
{..., warning = T} # preserve warnings? warning()
{..., error = T} # preserve errors? stop()
{..., message = T} # preserve messages? message()
{..., split = F} # split output into separate files?
{..., include = T} # execute it but include (or not) the chunk output in the final document (for example, generate the images)
{..., engine="bash"} # execute bash, python, awk, ruby, instead of R
# CHUNK OPTIONS code
{..., tidy = T} # tidy up R code
{..., comment=""} # remove any preceding text from console output, default =="##"
{..., prompt = F} # show prompt chars
{..., highlight = T} # highlight the source code?
{..., size='normalsize'} # default latex font size
{..., background='#F7F7F7'} # default latex background color
# CHUNK OPTIONS cache
{..., cache = TRUE} # only run the first time, delete the contents of the cache folder to rerun everything
{..., cache.path='cache/'} # cache dir
{..., dependson = NULL} # char vector of chunk labels (or numeric)
# CHUNK OPTIONS figure
{..., fig.path='figure/mcmc-'} # path prefix to image (avoid spaces), "figure/" by default
{..., fig.keep='high'} # keep high level plots (not abline, points, lines) (also, "none", "all", "first", "last")
{..., fig.show='asis'} # also, "hold" output them at the end of the code chunk, "animate" wrap all plots in the chunk into an animation
{..., dev='png'} # also, "pdf", you can create both dev = c("pdf", "png")
{..., dev.args = NULL} # dev.args = list(bg="yellow",pointsize = 10)
{..., dpi = 72} # dpi
{..., fig.width = 7} # width in inches
{..., fig.height = 7} # height in inches
{..., out.width="300px"} # final width (scaled), 3in, 8cm
{..., out.height="300px"} # final height (scaled)
{..., out.extra="angle = 90"} # rotate final image (doesn't work), out.extra = 'style="float:left;"'
{..., fig.align="default"} # don't align, or "left","center","right"
{..., fig.cap="caption"} # caption
{..., fig.scap="short.caption"} # short . ; :
{..., fig.lp="fig:"} # concatenate "fig:" and the chunk label
{..., fig.pos=""} # latex figure arrangement
# knitr inline
`r x`
#knitr read external file
read_chunk("script.r")
# convert a matrix to a bioconductor ExpressionSet
ExpressionSet(assayData = my_mat)
# heatmap decent defaults => library(gplots)
heatmap.2(mat,key = TRUE, keysize = 1, density.info="none", trace="none",scale="none",cexRow = 1, dendrogram="both", col = colorpanel(25,"#278DD6","#ffffff","#d62728"), margins = c(10,10), symbreaks = T)
# heatmap.2 options
Rowv = TRUE, Colv= FALSE, # sorting of dendrogram
dendrogram = c("both","row","column","none"), # show or hide
symm = FALSE, # is the matrix square?
# data scaling
scale = c("none","row", "column"), # row by default
na.rm = TRUE,
col = colorpanel(25,"steelblue","white","red"), # number of gradations and colorsk
labCol = NA, rowCol = NA, # to hide col/row labels
colsep = c(2,4,6), rowsep = c(15,25), # separate these rows/cols
sepcolor="white",
sepwidth = c(0.05,0.05), # percentage of row height
# density() computes a kernel density estimate. parameters:
bw # smoothing bandwith. the sd of the smoothing kernel
adjust # what is actually used: adjust*bw, this makes it easy to say use half the bandwith => adjust=.5
from,to # the left- and rigth-most points that must be estimated
# Row/Column Labeling
margins = c(5, 5),
ColSideColors,
RowSideColors,
cexRow = .3, cexCol = .3, # to make text smaller
labRow = NULL, labCol = NULL,
# example of colsidecolors rowsidecolors (single column, single row)
mat <- matrix(1:100, byrow = T, nrow = 10)
column_annotation <- sample(c("red", "blue", "green"), 10, replace = T)
column_annotation <- as.matrix(column_annotation)
colnames(column_annotation) <- c("Variable X")
row_annotation <- sample(c("red", "blue", "green"), 10, replace = T)
row_annotation <- as.matrix(t(row_annotation))
rownames(row_annotation) <- c("Variable Y")
heatmap.3(mat, RowSideColors = row_annotation, ColSideColors = column_annotation)
# multiple column and row
mat <- matrix(1:100, byrow = T, nrow = 10)
column_annotation <- matrix(sample(c("red", "blue", "green"), 20, replace = T), ncol = 2)
colnames(column_annotation) <- c("Variable X1", "Variable X2")
row_annotation <- matrix(sample(c("red", "blue", "green"), 20, replace = T), nrow = 2)
rownames(row_annotation) <- c("Variable Y1", "Variable Y2")
heatmap.3(mat, RowSideColors = row_annotation, ColSideColors = column_annotation)
key = TRUE, keysize = 1,
density.info="none",
denscol = tracecol,
symkey = min(x < 0, na.rm = TRUE) || symbreaks,
densadj = 0.25,
# plot layout
lmat = NULL, # position of color key, col dendrogram, row dendrogram and heatmap (also rowsidecolors and colsidecolors)
lhei = c(.2,1,.7), # column height of each of the prev. elements
lwid = NULL # column width of each of the prev. elements
# random number between x and y
runif(1,x,y)
# replace elements of a matrix or data frame based on some condition
# head(qpcr)
# gene_symbol CX8E_day_2 CX8E_day_3 CD8J_day_3 CX8C_day_3
# 1 IL1B -3.84 -12.82 -5.17 -6.19
# 2 IL6 -2.73 -2.10 -1.27 1.06
# 3 IL21 -2.73 -2.10 -1.27 1.06
replace(qpcr[,-1],qpcr[,-1]>50,50)
# display all brewer palettes: sequential (low:light, high:dark), qualitative (categorical), diverging (mid-range:light, low and high:dark)
display.brewer.all()
# brewer colors
library(RColorBrewer)
colorRampPalette(brewer.pal(7,"Set1"))(100)
# MDS plot
d <- dist(t(mat))
mds <- cmdscale(d)
cols <- as.factor(timepoints)
plot(mds, col = as.numeric(cols), pch = 20, cex = 1.5)
par(xpd=TRUE); legend("bottomright", levels(timepoints), lty = 1, lwd = 5, col = seq(along = levels(timepoints)))
# point size
plot(..., cex = 1.5)
# intersect arrays
union(a,b)
intersect(a,b)
setdiff(a,b) # in a but not in b
setequal(a,b)
# adjust p value BH
p.adj.value <- p.adjust(p.value,method="BH")
# deal with NAs in t-test
obj <- try(t.test(day_0, day_3), silent = TRUE)
if (is(obj, "try-error")) return(NA) else return(obj$p.value)
# exit without making noise
capture.output(return())
# deal with errors
tryCatch(source("http://www.bioconductor.org/biocLite.R"),error = function(e)e)
# png is in pixels and pdf in inches
png(filename, width = 800, height = 800)
pdf(filename, width = 8, height = 10)
# select or slice data frame by column names or row names
df[, c('column_name_1','column_name_2','column_name_3')] # only select, can't remove
subset(df,select=-c(column_name_1,column_name_3)) # negative selection by name
subset(df,select = column_name_1:column_name_3) # select by ranges
subset(df,select=-column_name_0)
subset(df,select=-GeneName) # no quotes!
subset(df,select = c(column_name_1,column_name_3))
subset(df,select = c(column_name_1,3)) # you can combine names and numbers
subset(df, select = grep("col", colnames(df))) # subset by grepping
gene_name_mapper$GeneName[which(gene_name_mapper$ProbeName %in% d$ProbeName)] # select using %in%
# subset by row remove rows by rowname
raw_qpcr[!rownames(raw_qpcr) %in% c("HGDC","RTC1","RTC2","PPC"),]
remove_rownames(df,rownames_to_remove)
# categorical x axis
every_other <- function(labs,side = "x",...){
l <- labs[seq(1,length(labs),by = 2)]
if (side == 'x'){
return(scale_x_discrete(breaks = l,labels = l,...))
}
if (side == 'y'){
return(scale_y_discrete(breaks = l,labels = l,...))
}
}
x_angle <- theme(axis.text.x = element_text(size = 7,
hjust = 0,
vjust = 1,
angle = 310))
p + x_angle + every_other(levels(dat$x))
# for each element in a, it checks if it's also in b
a %in% b
# substitute
names <- sub("Perez","Pérez",names)
# read from clipboard
a <- read.table("clipboard")
# sort dataframe by the same column of a different data frame
just sort them individually
# sort dataframe by column name
df[order(-df$z), ] # doesn't work on matrix ?
df[with(df, order(-z)), ] # doesn't work on matrix ?
df[with(df, order(-z, b)), ] # several columns
# with
with(pbmc_ce[[2]], fit[fit$genes$GeneName=="HSPA1B",]$coefficients)
# sort dataframe by row names or column names
dat[order(rownames(dat)),order(colnames(dat))]
# sort dataframe by column number
df[order(-df[[3]]),]
df[order(df[[3]],decreasing = TRUE),,drop = F]
# (sort) get the top result of matrix by column 5 decreasing
probabilities[probabilities[,5] == max(probabilities[,5]),]
probabilities[order(-probabilities[,5]),][1,]
# uniquify a vector
a <- c("a","a","b","c","c","c")
dups <- duplicated(a)
a[dups] <- paste0(a[dups], "_", 1:sum(dups)) # "a" "a_1" "b" "c" "c_2" "c_3"
# remove levels drop levels after subsetting
df <- droplevels(df)
df$subsetted_lsit <- factor(df$subsetted_list) # pre r 2.12
# wide to long. id: non-changing columns, variable_name: name of indexing column (otherwise it uses "variable")
library(reshape)
mdf <- melt(df, id = c("probe_id", "accession_number", "gene_name", "gene_description", "p.value"), variable_name="Experiment")
# melt using rownames, adds rownames as a column
melt(as.matrix(df_with_rownames))
# shuffle a vector
sample(x,length(x))
# melt with split by variable name, create a new dataframe
# names(res): "X" "Alpha" "Lambda" "Elastic.Net.Mean" "Elastic.Net.Std" "LM.Mean" "LM.Std"
res_m <- res[,c(1,4:7)]
res_m <- melt(res_m, id = c("Gene"))
res_m$variable <- sub("Elastic.Net","Elastic_Net",res_m$variable)
res_m <- with(res_m, data.frame(
Gene = Gene,
model = unlist(strsplit(variable,"\\."))[1],
statistic = unlist(strsplit(variable,"\\."))[2],
value = value))
# even better
res_m <- data.frame(
Gene = rep(res$X, times = 2),
model = c(rep("Elastic Net", times = nrow(res)), rep("Linear Model", times = nrow(res))),
mean = c(res$Elastic.Net.Mean, res$LM.Mean),
sd = c(res$Elastic.Net.Std, res$LM.Std)
)
# use this page to update R or you'll get problems with libiconv
http://r.research.att.com/
# read arguments
args <- commandArgs(T)
input_name <- args[1]
R --slave --vanilla < script.R
R CMD BATCH infile.R outfile
# Plot a bar chart when one of your variables gives the height (use stat identity) bar plot
ggplot(iron, aes(cluster,size)) + geom_bar(stat="identity")
ggplot(rna, aes(life_stage,reads, fill = type)) + geom_bar(stat="identity") # stacked bars
# bar chart with error bars
stdev_coords <- aes(ymax = mean_error + sd_error, ymin = mean_error - sd_error)
p <- ggplot(res_m, aes(x = gene, y = mean_error, fill = model)) +
geom_bar(position="dodge", stat="identity") +
geom_errorbar(stdev_coords, width = 0.1, position="dodge")
# ggplot summary stats
stat_summary(fun.data="mean_cl_normal", aes(colour = gene), geom="line", size = 1.5, width=.1, mult = 1) # mean_cl_normal comes from Hmisc smean.cl.normal, use mult = 1 to avoid extra margins
stat_summary(fun.data="mean_cl_boot", aes(colour = gene), geom="pointrange")
stat_smooth(aes(colour = gene), method="loess", se = F, size = 1.5)
# add contour around geom_bar
geom_bar(color="black")
# standard deviation sd ggplot
data # x = timepoints, y = m_values, so std_devs needs the m_values column (that's where the point appears)
std_devs <- ddply(data, .(gene, timepoints, virus),function(x) data.frame(m_values = mean(x$m_values), sd = sd(x$m_values), se = se(x$m_values), ymin = mean(x$m_values)-sd(x$m_values), ymax = mean(x$m_values)+sd(x$m_values)) )
p + geom_pointrange(aes(colour = gene, ymin = ymin, ymax = ymax, group = gene), data = std_devs, position = position_dodge(.3))
# rename columns dataframe
x <- c("a" = 1, "b" = 2, d = 3, 4); rename(x, c("d" = "c"))
rename(df, c(old_name1 = "new_name1", old_name2 = "new_name1", old_name3 = "new_name2"))
# remove null entries from a list
compact(list(3,NULL))
# [[1]]
# [1] 3
# remove names
unname(vector)
# uninstall a package
remove.packages("package_name")
# To index by coords (row and col): rename MAwin$M, then generate those names for the new "top"
rownames(ce_lassa$MAwin$M) <- paste0(ce_lassa$MAwin$genes$GeneName, "_", ce_lassa$MAwin$genes$Row, "_", ce_lassa$MAwin$genes$Col)
ce_lassa$bad_top_coords_d3 <- na.omit(ce_lassa$all[ce_lassa$all$P.Value < .005, c("Row","Col", "GeneName", "ProbeName")])
ce_lassa$bad_top_coords_d3 <- paste0(ce_lassa$bad_top_coords_d3$GeneName, "_", ce_lassa$bad_top_coords_d3$Row, "_", ce_lassa$bad_top_coords_d3$Col)
ce_lassa$bad_top_d3_M <- ce_lassa$MAwin$M[ce_lassa$bad_top_coords_d3,]
# then, to extract the gene_names
library(stringr)
bad_genes <- sapply(rownames(ce_lassa$bad_top_d3_M), function(x) str_match(x,"(^[^_]+)")[1])
# limma duplicate correlation time series longitudinal (but you can't have weird designs...)
# When the time course is of a repeated measures nature, you can estimate the correlation between the repeated measures using the duplicateCorrelation() function in limma, with the block argument indicating each time course replicate. The correlation is then input to the lmFit() function and carried through all the analysis.
# install from github
install_github("knitr","yihui")
load_all("path_to_downloaded_package", reset = T)
# add manual palette ggplot
categorical_10 <- c("#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf")
+ scale_fill_manual(values = categorical_10)
+ scale_colour_manual(values = categorical_10)
categorical_8 <- c("#999999", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")
# string length string number of characters
nchar(str)
# Save a graph
ggplot(reads_by_life_stage, aes(life_stage,reads, fill = type)) + geom_bar(stat="identity")
cat("Saving..."); filename <- paste0("plots/reads_by_life_stage.png");ggsave(filename, width = 8, height = 6)
message("\rSaved: ", filename)
filename <- paste("cdon.png", sep="");png(filename,width = 1024,height = 500,units="px",bg = "transparent")
print(p)
dev.off(); print(paste("Saved:", filename))
# Add points with different aes to an existing graph
ggplot(clusters,aes(V1,V2)) +
geom_point(data = clusters, aes(V1,V2,col = V4,shape = V3+15,size = 7)) +
geom_point(data = centroids, aes(V1,V2, col = V3),size = 10, inherit.aes = F)
# Remove legend ggplot
theme(legend.position="none")
# legend ggplot
theme(..., legend.position="bottom", legend.direction="horizontal", legend.box = "vertical")
# Increase ggplot outer margins (x-right:1, x-left:1, y-top:0.5, y-bottom:0.5)
library(grid); theme(plot.margin = unit(c(1,1,25,25), "lines")) #TRBL
theme(...axis.title.y = element_text(vjust=-.5), plot.margin = unit(c(1,1,1,2), "lines")) # great to add margin to y label y axis label
# plot two ggplots
plot1 <- plot_jitter( cfg(gfc(plot_probes), ce_lassa2), list(ce_lassa2), show_points = F, show_sd = F)
plot2 <- plot_jitter_qpcr(plot_probes,qpcr)
grid.arrange(plot1, plot2, ncol = 2)
# opts => theme
# rotate x axis 90 degrees vertical (ggplot)
theme(axis.text.x = element_text(angle = 90, hjust = 1)) #hjust = 0 is left align, hjust = 1 is right aligned
theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1))
# rotate axis labels
plot(..., las = 1)
axis(1, las = 2)
# vjust: negative values the text away from the axis
# transparent opacity
rgb(255,0,0,75, maxColorValue = 255) # transparent red or just use "#FF00004B"
rgb(0,0,0,75, maxColorValue = 255) # transparent black or just use "#000004B"
# arrows
arrows(start_x, start_y, end_x, end_y, length=.1, angle=20, lwd=3, col = transparent("red", alpha=.3))
## ggplot opacity
alpha = 1/4
# Group and facet
ggplot(sub_m_cu,aes(codon,rf, group = gene, color = gene)) + geom_line() + facet_wrap(~aa, scale="free_x")
ggplot(global_rf, aes(codon,rf)) + geom_line(aes(group = aa, color = aa), size = 2) + facet_grid(. ~ aa, scale="free_x", space="free") + p_global_opts + ylim(0,1)
# Limit axis
ggplot(maa_current,aes(codon,value, group = gene, color = cluster)) + ylim(0,1)
# custom labels ggplot
scale_y_continuous(labels = function(x) format(10^x, digits = 2)) +
# transparent jitter and summary line
ggplot(myaa_cc, aes(reorder(codon,rf,sum),rf, group = gene)) + geom_line(alpha = 1/15, position = jit) + stat_summary()
# Hide all the gridlines
bp + theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank())
# annotate individual facets
annotation <- data.frame(experiment = c("1-Control Proestrus"), Sample = 41, Average = 3, label = c("34.4"))
p <- p + facet_grid(. ~ experiment, scales = "free")
p + geom_text(aes(label = label), data = annotation)
starts <- c(1.5,3.5,2.5)
reference <- data.frame(x1 = starts, x2 = starts+1, virus = c("lassa","ebola2","marburg"))
reference$virus <- factor(reference$virus, levels = c("lassa","ebola2","marburg"))
# decent venn diagrams
library(bvenn)
bvenn(get_combined_variable(all,"top_genes"), colors = brewer.pal(7,"Set3"))
# uneven time series annotations, color gradient jitter
p + geom_jitter(aes(x = dpi, y = log2_ratio, col = log2_ratio), position = position_jitter(width=.1), size = 4) + # make sure that aes() isn't set in ggplot(), but in the geometry
scale_colour_gradient(high="#BB232F",low="steelblue") +
facet_grid(. ~ virus, scale="free_x", space="free") +
geom_rect(data = reference,aes(xmin = x1, xmax = x2, virus = virus), ymin=-Inf, ymax = Inf, fill="grey", alpha=.4)
# change facet text
theme(strip.text.x = element_text(...))
# remove facet strips
theme(strip.text.x = element_blank(), strip.background = element_blank())
# theme text
element_text(family = "", face = "plain", colour = "black", size = 10, hjust = 0.5, vjust = 0.5, angle = 0, lineheight = 1.1)
# split string
unlist(strsplit("a.b.c",".", fixed = T)) # literally
unlist(strsplit("a.b.c","\\.", fixed = F)) # regexp
# array contains includes element?
v <- c('a','b','c','e')
'b' %in% v ## returns TRUE
any(v=="b")
match('b',v) ## returns the first location of 'b', in this case: 2
# sort strings with embedded numbers
library(gtools)
mixedsort(levels(m$dpi))
# [1] "day_0" "day_1" "day_3" "day_6" "day_8" "day_10" "day_12"
# average mean by groups
aggregate(value ~ group, molten_df, mean) # molten_df$value, molten_df$group
# if you want to aggregate by some of the columns, but not all
a <- data.frame(probe = c("probe1","probe2","probe3","probe4"), gene = c("gene1","gene1","gene2","gene1"), value = c(.001,.1,.05,.001))
# probe gene value
# 1 probe1 gene1 0.001
# 2 probe2 gene1 0.100
# 3 probe3 gene2 0.050
# 4 probe4 gene1 0.001
aggregated <- aggregate(value~gene, data = a, FUN = min)
# gene value
# 1 gene1 0.001
# 2 gene2 0.050
b <- merge(aggregated, a) # YOU MIGHT STILL GET DUPLICATE GENES AT THIS STAGE becase probe1 and probe4 had the same value
# gene value probe
# 1 gene1 0.001 probe1 ***
# 2 gene1 0.001 probe4 ***
# 3 gene2 0.050 probe3
b <- merge(aggregate(value~gene, data = a, FUN = min), a)
aggregate(b, by = list(b$gene), function(x) x[1])[,-1]
# gene value probe
# 1 gene1 0.001 probe1
# 2 gene2 0.050 probe3
ddply(a, .(gene), function(x) x[which.min(x$value),]) # more elegant, but too slow with a big dataframe
# ddply is slow
# 11:23:01 > h(mulatta$mnc)
# gene_symbol sample counts lane monkey timepoint
# 14925 5_8S_rRNA l1_m1_d0 529.241 l1 m1 d0
# 32255 5_8S_rRNA l1_m1_d3 3633.144 l1 m1 d3
a <- ddply(mulatta$mnc, .(gene_symbol,timepoint), summarize, median = median(counts)) # too slow
a <- aggregate(counts~gene_symbol+timepoint, data = mulatta$mnc, median) # do this
dcast(a, gene_symbol ~ timepoint, value.var="counts") # to unmelt
# write data frame to file
write.table(ratList, file = "ratList.csv", sep = ";", quote = F, row.names = F, col.names = F)
# write text to a file
writeLines(text,file)
# write data frame to clipboard
pbcopy(data)
# to read data with gene descriptions, disable quotes, using @ is also advised because sublime text merges trailing tabs (not a problem if you don't have empty fields)
ensembl_info <- read.table("/Users/nacho/Documents/BU/Connor/projects/cmf/raw_data/genome/ensembl_69.txt",sep="@", quote="")
# read data from clipboard
a <- read.table(pipe("pbpaste"))
# don't add X to column names
read.table("path.txt", check.names = FALSE)
# histogram vs density plot
plot((density(na.omit(ce_lassa$all$P.Val)))) # doesn't allow NAs, you can change the bw of density(). Ex: bw=.1
hist(ce_lassa$all$P.Val, breaks = 50)
# numerical differentiation derivative
x <- -4:4
y <- x^2
f <- splinefun(x,y)
plot(x,y, type="b")
lines(x,f(x,deriv = 1))
# super hack to show filled squares instead of lines in legend
GeomLine2 <- proto(GeomLine, {
objname <- "line2"
guide_geom <- function(.) "polygon"
default_aes <- function(.) aes(colour = "black", size = 0.5, linetype = 1, alpha = 1, fill = "grey20")
})
geom_line2 <- GeomLine2$build_accessor()
g_qpcr <- ggplot(m_qpcr, aes(experiment, value, group = probe_id, color = gene_name, fill = gene_name))
g_qpcr <- g_qpcr + geom_line2(aes(size = log(1/p_value)))
# don't convert strings to factor
data.frame(... stringsAsFactors = F)
# reorder the levels of a factor
f <- factor(c("a","b","c"), levels = c("c","a","b"))
df$factor <- factor(df$factor, levels = c("c","a","b"))
unordered_factor <- relevel(unordered_factor, "Ref") # relevel with a new reference value (puts the reference value first)
reorder(f, c("c","a","b")) # you need to specify every item in f in the right order,
raw$dpi <- factor(raw$dpi, levels = mixedsort(levels(raw$dpi))) # using day_0, day_3 from gtools
# rename levels
# Rename by name: change "beta" to "two"
levels(x)[levels(x)=="beta"] <- "two"
# Rename by index in levels list: change third item, "gamma", to "three"
levels(x)[3] <- "three"
# Rename all levels
levels(x) <- c("one","two","three")
# Rename all levels, by name
x <- factor(c("alpha","beta","gamma","alpha","beta"))
levels(x) <- list(A="alpha", B="beta", C="gamma")
# "A" "B" "C"
# This only works if ALL levels are set in the list; if any are not in the list,
# they will be replaced with NA
# make a factor ordered
f <- factor(c("a","b","c"), levels = c("c","a","b"), ordered = T)
data$f <- ordered(data$f, levels = c("c","a","b"))
# cool ggplot docs
http://had.co.nz/ggplot2/docs/
# rename axis title
scale_y_continuous(name="Fold Change")
# increase font size and maintain vertical
theme(axis.title.y = element_text(size = 20, angle = 90, face="bold"))
# use decent sizes
g_qpcr <- g_qpcr + theme(plot.title = element_text(size = 25), axis.text.x = element_text(angle=-90, hjust = 0, size = 20), axis.title.y = element_text(size = 20, angle = 90), axis.title.x = element_text(size = 20), axis.text.y = element_text(size = 20))
# To build a dataframe in R by reading from a shell pipe
data <- read.table(pipe("cat /dev/stdin"))
> cat my_data | Rscript reader.R
# To use a shell command and "interpolate" an R variable
system(paste("echo",myLongString,"|pbcopy"),intern = T)
pattern_variable <- "big_file_*"
paths <- system(paste("ls",pattern_variable), intern = T)
paths
> big_file_1 big_file_2 big_file_3
# insert a string inside another string: (use sub?)
path <- "dir/my_file"
randomized_path <- system(paste("echo ", path, " | sed 's/\\(.*my_\\)/\\1randomized_/'", sep=""), intern = T)
randomized_path
dir/my_randomized_file
# open in sublime
system("subl qpcr_pairwise_proestrus.csv")
# find out size of current device window
dev.size(units="px")
# new device
dev.new(width = 5, height = 4)
# you can't change axis position (top, right)
# reduce number of significant positions decimals, round
signif(df,4)
format(df, scientific = F)
format(df, digits = 3)
format(.323,digits = 1) # 0.3
format(.001,digits = 1) # 0.001
options(digits = 2)
# install a bioconductor package
source("http://www.bioconductor.org/biocLite.R")
biocLite("limma")
biocLite("DESeq")
biocLite("org.Hs.eg.db")
# get current version of package
packageVersion('knitr')
sessionInfo()
installed.packages()
packageDescription("ggplot2")["Version"]
# list of loaded packages
(.packages())
# reset par()
dev.off()
# return multiple arguments, load multiple arguments
lapply(list("a","b"), function_that_returns_two_arguments)
# par good practice
old_par <- par()
par(mfrow = c(1,2)) # multiple plots
plot(a)
plot(b)
par(old_par)
# conditional color
plot(..., col = ifelse( fit$padj < p.value.cutoff, "red", "black" ))
## Frequency tables ##
# 1. (case=>table) If you start with a dataframe in case form, you can convert to table form by using table():
repeated.rows <- data.frame(smoker = c("Y","Y","Y","N","N"), diagnosis = c("cancer","cancer","nothing","nothing","cancer"))
# smoker diagnosis
# Y cancer
# Y cancer
# Y nothing
# N nothing
# N cancer
with(repeated.rows, table(smoker,diagnosis))
# diagnosis
# smoker cancer nothing
# N 1 1
# Y 2 1
# 2. (frequency=>table)If you start with a dataframe in frequency form, you can convert to table form by using xtabs():
melanoma
# type site count
# 1 1 h 22
# 2 1 t 2
# 3 1 e 10
# 4 2 h 16
# 5 2 t 54
# 6 2 e 115
T_melanoma <- xtabs(count~type+site, melanoma)
# site
# type e h t
# 1 10 22 2
# 2 115 16 54
# 3 73 19 33