R语言学习(一)

 大年初一,看了看春晚的开头,闲极无聊,正好手边有从同事那借来的《学习R》这本书,那就学学吧,说不定以后会用到,顺便逃避爸妈催婚,单身狗的春节就是受虐!(PS:公司老大常常说我,学那么多东西,用不到,有啥用?我没有反驳过,其实我一直想说,如果我不学,恐怕永远不会有机会用到!)
 从哪开始呢?安装?IDE? 很简单,IDE使用Rstudio 就可以啦,原因?很流行,大家都在用,就这么简单!
    #序列
#生成序列,可指定步长
seq.int(1,10,2)
seq.int(0.1,0.01,-0.01)

#seq_len() 
#seq_along() 创建一个从1开始、长度为其输入值得序列
pp <- c("this","is","a","test","!!!")
for(i in seq_along(pp)) print(pp[i])
#长度 length()
length(pp)
nchar(pp) #序列中每个字符串的长度
#矩阵 matrix
x <- matrix(1:6,nrow = 3,ncol = 2)
#创建矩阵 4*3 ma
matrix(1:6,nrow = 4,ncol = 3,dimnames = list(c("one","two","three","four"),c("ein","zwei","drei")))
#byrow = TRUE 按行填充
matrix(1:12,nrow = 4,byrow = TRUE,dimnames=list(c("one","two","three","four"),c("ein","zwei","drei")))

#矩阵维度 dim
dim(x)

#绝阵属性
attributes(x)

#创建矩阵
y <- 1:6
dim(y) <- c(2,3) #2 row 3col

#矩阵拼接
y1 <- matrix(1:6,nrow = 2,ncol = 3)

rbind(y,y1)#行拼接
cbind(y,y1)#列拼接
#转置矩阵
t(x)
# 内乘 %*% 外乘%o%
#列表 和向量vector最大的不同:list可以存储不同类型的数据
l <- list("a",2,10,3+4i,TRUE)

#列表元素命名 类似于map
l1 <- list(a=1,b=2,c=3)

l2 <- list(c(1,2,3),c(4,5,6,7))

#矩阵命名

x <- matrix(1:6,nrow = 2,ncol = 3)

dimnames(x) <- list(c("a","b"),c("c","d","e"))
#数组
x <- array(1:24,dim = c(4,6))
#4个两行3列的矩阵
x1 <- array(1:24,dim = c(2,3,4))
#数据框
#创建
df <- data.frame(id = c(1,2,3,4),name= c("a","b","c","d") , gender = c(TRUE,FALSE))

#行 列
nrow(df)
ncol(df)

df2 <- data.frame(id = c(1,2,3,4),score=c(80,80,90,100) )

#转换成矩阵
data.matrix(df2)
#因子

x <- factor(c("female","female","male","male","female"))

y <- factor(c("female","female","male","male","female"),levels = c("male","female"))
#因子属性
table(x)
#去掉属性
unclass(x)

#缺失值 NA/NAN  NAN只表示数值缺失 NA是有属性的
#is.na() is.nan()
x1 <- c(1,NA,2,NA,3)
is.na(x1) #NA 返回true

gl()#生成因子水平
gl(3,1,6,labels = c("A","C","B"))#交替
#日期

x <- date()
#字符串
class(x)

x2 <- Sys.Date()
class(x2)

x3 <- as.Date("2016-02-06")
weekdays(x3) #星期
months(x3) #月份
quarters(x3) #季度
julian(x3) #距离1970 01 01 多少天

#运算
x4 <- as.Date("2015-09-03") 
#相差多少天
x4-x3
as.numeric(x4-x3) #只输出数值

#时间
x <- Sys.time()

p <- as.POSIXlt(x)

class(x)
names(unclass(p))

p$sec
p$min
p$hour

as.POSIXct(p)
#字符串转换为时间
x1 <- "2016-02-06 00:37"
strptime(x1,"%Y-%M-%d %H:%M")
posted @ 2016-02-08 14:57  傾聽雨落  阅读(196)  评论(0编辑  收藏  举报