R语言初学笔记3

来源:互联网 发布:半条命1网络电影 编辑:程序博客网 时间:2024/06/06 02:22

得空,那边R在处理些数据,估计得要一天左右时间,不得不喷下R的循环for语句,慢!
言归正传,下面说下我这段时间遇到的问题,解决方法。

1.R语言添加列名

colnames(data)=c("xx","oo","pp") 

data是你需要修改列名的数据,若是多个列名,则需要c()

2.R语言 修改单个列名
有时候,可能只需要修改单个列名,如果采用上面这种方法则太费事,可以使用:
names(data)[col_num] <- "m" ,意思是将data数据的第col_num个列名修改为m

3.填补缺失值
mdd[is.na(mdd)]<- 0 ,将mdd数据中所有为NA的值替换为0,NA是一个逻辑值,不可使用==作为判断依据

4.R语言求平均数(每行,每列)
例如:
data:
1 1 4
3 4 7
,data 为2*3的数据,求每列和,你可以使用
sum(data[,i]),求行sum(data[i,]),其中i表示数字.
你也可以使用apply家族函数
求每行的和

apply(data,1,sum)

求每列的和

apply(data,2,sum)

其中1表示行,2表示列,比sum简便多了吧,sum可以改成mean等函数,具体的可以help(“function”)一下,其中function为你需要查找的函数

5.R语言 查找满足条件的数据
目前为止,我采用的是which语句

which(mdd$user_id==14581)

意思是查找mdd数据中user_id等于14581的数据,这里返回的是一组行编号
1 2 5 6 7 8 等等,你可以采取嵌套的方法直接获取每行的数据

mdd[which(mdd$user_id==14581),]

这里就是得到user_id为14581的所有数据了

6.R语言 随机抽取样本

mydata[sample[5400,10],]

意思为 从mydata 5400个样本数据中,随机抽取10个样本
7.R语言 求交集 并集 等

intersect(u1,u2)u1u2交集union(u1,u2)u1 u2并集unique(u1)u1中不重复的元素 例如:1 1 2 3 3 3 会得到1 2 3

8.R语言 返回多个结果

t = array()for(i in 1:3){  t[i]=i  a = list(t)}return (a)

此处返回a这个list,你也可以采用unlist t(转置) 等操作转换到你需要的格式

9.R语言 排序
例如:

d1 <- c(2,3,8,4,5,6)d1[order(d1)] [1] 2 3 4 5 6 8 

当然,你也可以使用sort(d1) 可以达到同样的效果,而且sort函数还有一个好处,就是返回下标
sort(d1,index.return =TRUE)

10.R语言 去除科学计数法 保留小数位

    options(scipen=3)    options(digits=3)

11.R语言 中文乱码问题
Rstudio中文乱码 file–reopen with encoding 再选择utf-8就ok了

"Not enough finite obervations" is an error returned by cor.test under certain circumstances. If you take a look a the cor.test.default source code, you'll see :OK <- complete.cases(x, y)x <- x[OK]y <- y[OK]n <- length(x)cor.test removes NA values from you vectors [...]if (method = "pearson") {    if (n < 3L)         stop("not enough finite obervations")[...]else {    if (n<2)        stop("not enough finite obervations")If your vectors do not contain enough non-NA values (less than 3), the function will return the error.Make all of the columns in your dataframe contain enough non-NA values before you use cor.test.I hope this will be useful.

这是我遇到的一个问题,查找相关资料得到问题所在:向量中包含过多NA,非NA数量少于3个,如果你出现此类情况,请先检查一下向量。

                             若有问题,请指出,谢谢!
1 0