R统计方法整理1.1

R函数

平均值,中位值,模式

mean()求平均值

mean(x, trim = 0, na.rm = FALSE, ...)

x是输入向量。
trim用于从排序向量的两端丢弃一些观察结果。
na.rm用于从输入向量中删除缺失值。
median()

x <- c(12,7,3,4.2,18,2,54,-21,8,-5)
直接输出平均值
result <- mean(x)
result.mean <- mean(x)
输出:
print(result.mean)
#直接输出名字也可以输出
result

#修剪,会先排序,然后去掉左右两边最大最小前三名,再求平均值
result.mean <-  mean(x,trim = 0.3)
# 去除NA值  na.rm = TRUE
result.mean <-  mean(x,na.rm = TRUE)

Median( )中位数

median(x, na.rm = FALSE)

x是输入向量。
na.rm用于从输入向量中删除缺失值。

Mode模式

可以包含数字,字符,自定义编写输出出现次数最多的值

# Create the function.
getmode <- function(v) {
   uniqv <- unique(v)
   uniqv[which.max(tabulate(match(v, uniqv)))]
}

# Create the vector with characters.
charv <- c("o","it","the","it","it",1,3,5)

# Calculate the mode using the user function.
result <- getmode(charv)
print(result)

线性回归

回归分析用于建立两个变量之间的关系模型
预测变量X,响应变量Y

y = ax + b

y是响应变量。
x是预测变量。
a和b被称为系数常数。

建立回归的步骤

收集已有的两个变量数据
lm()函数创建关系模型
从创建的模型中找到系数,并用这些创建数学方程
获得关系模型的摘要以了解预测中的平均误差(残差)
预测新值,predict()函数

lm()函数
lm(formula,data)

公式是表示x和y之间的关系的符号。
数据是应用公式的向量。

predict()函数
predict(object, newdata)

object是已使用lm()函数创建的公式。
newdata是包含预测变量的新值的向量。

举例
# The predictor vector.
x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)

# The resposne vector.
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)

# Apply the lm() function.
relation <- lm(y~x)

# Find weight of a person with height 170.
a <- data.frame(x = 170)    ???这里用到一个数据框
result <-  predict(relation,a)
print(result)
图形方式可视化回归
# Create the predictor and response variable.
x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)
relation <- lm(y~x)

# Give the chart file a name.
png(file = "linearregression.png")

# Plot the chart.
plot(y,x,col = "blue",main = "Height & Weight Regression",
abline(lm(x~y)),cex = 1.3,pch = 16,xlab = "Weigh
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值