R语言的一些笔记

在使用R语言中,有好多问题,此文会持续的记录一些遇到的问题及解决方法。

1,在终端打印矩阵或数据框时,打印的列数太少,尤其是对宽屏幕,更是浪费。

在R的options()函数中有参数width,可以设置打印的列数,width参数解释如下:
所以可以设定options(‘width’=200)来增加打印的宽度。
例如:

sink("out.txt")
options('width'=200)
print(out)
sink()

这样可以保证对齐,输出数据的美观。

那怎么得到原来的width呢,只要使用getOption(‘width’)即可,用完还可再还原回去。关于options()的其他参数,使用到了,再补充进来。

2,将list转换成matrix或data.frame

这些资料也是在网上找到的,属于摘抄:

x <- c("34,string,23", "2,sl,32")
y <- strsplit(x, ",")
y  # 可是此时我想统一使用每个元素的第一个数(34,2)作为一个向量赋值,行不通
# [[1]]
# [1] "34"     "string" "23"
#
# [[2]]
# [1] "2"  "sl"32”
y_matrix<-do.call(rbind, y)
# 注意转换前y最好为m*n的完整list,否则y缺少的部分将被循环补齐
y.matrix
#     [,1] [,2]     [,3]
# [1,] "34" "string" "23"
# [2,] "2"  "sl"     "32"

使用do.call()去合并list中的元素
另外一种说法是data.frame也是list,所以可以很方便的转成data.frame

y2 <- as.data.frame(y)
y2
  c..34....string....23.. c..2....sl....32..
1                      34                  2
2                  string                 sl
3                      23                 32

还有就是可以将list中每个元素的某一个元素提取出来的方式:

y3 <- sapply(y, "[[", 1) 
y3
[1] "34" "2"
3,将字符矩阵转成数字矩阵
# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))  
# 或者使用下面这种方式
matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))
# 另外还有中比较简单的方式,这种方式比较粗暴
mode(SFI) <- "numeric"
4,ggplot2中的一页多图

ggplot2在生成一页多图方面,有分面的命令(facet),可以自动根据分组,每组对应一幅图出来,属于同种类型的作图。但是,如果是不同类型的图,想拼到一起,就比较麻烦了。

提供的方法摘自:http://www.anaharb.com/2014/0228/R-grid-n-into-1/

第一种使用的grid包

library(ggplot2)
library(grid)
#generate a new page, or erase the current one.
grid.newpage()
#maintain a Viewport tree, which describe the regions and coordinate systems.
pushViewport(viewport(layout=grid.layout(1,2)))
#generate two ggplot2 objects.
a <- qplot(TMPRSS4, ECADHERIN, data=spear)
b <- qplot(TMPRSS4, ECADHERIN, data=spear, geom="jitter")
#print them into the Viewport, or the page.
print(a, vp=viewport(layout.pos.row=1,layout.pos.col=1))
print(b, vp=viewport(layout.pos.row=1,layout.pos.col=2))
#also, you can define a function to make the print process more concise.

第二种是使用gridExtra包

library(gridExtra)
a <- qplot(TMPRSS4, ECADHERIN, data=spear)
b <- qplot(TMPRSS4, ECADHERIN, data=spear, geom="jitter")
grid.arrange(a,b,ncol=2)

测试了下,还是第二种方法比较好,建议熟悉下gridExtra,关于分页的要求基本都能满足。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值