r - 我似乎找不到正确的方法来索引前一个向量的平均值
问题描述
我目前正在处理一个家庭作业问题,该问题要求我将先前向量的平均值索引到新向量中。在选择前一个向量的平均值时,教师希望我们只选择所述平均值的 +-2 的元素。请看下面的问题。
从 rnorm.vector 中,仅选择值在平均值±2 标准差内的元素。将此新向量分配给变量 rnorm.select.vector 并显示该向量。
我尝试使用 [] 和其他索引标准
// Normal distribution of 30 numbers with a mean of 25 and Standard Deviation of 2.5
rnorm.vector <- rnorm(30, mean = 25, sd = 2.5)
// logical vector
rnorm.logical.vector <- (rnorm.vector >= 25)
rnorm.logical.vector
// +- 2.5 of standard Deviation
rnorm.select.vector <-
我似乎无法在没有错误的情况下获得正确的结果
解决方案
因为我非常喜欢猫,所以我尝试举一个小例子,说明如何使用逻辑向量从现有向量中选择所需的元素(可以是猫名、随机数等)
# i got a list of my cats name
my_cats_names <- c("Boby", "Tara", "Petzi", "Felix", "Mauzi", "Schnurrli")
# and a coresponding list with my cats weight
my_cats_weight <- c(8, 4, 7, 5, 4, 5)
# so Boby has 8kg, Tara 7 and so on
# During last night someone has stolen my ham, and im suspecting one of my cats to be the thief.
# Since it was a big ham im pretty sure it needs a cat of at least 6kg to steal and eat it,
# so i want to select all my cats that are 6kg or more from my list.
which_one_is_over_6_kg_logical_vector <- my_cats_weight >= 6
which_one_is_over_6_kg_logical_vector
# > which_one_is_over_6_kg_logical_vector
# [1] TRUE FALSE TRUE FALSE FALSE FALSE
# This result tells me, that the first one in the list is over 6kg, the second one not the 3rd one is over and so on
# Now i can use the logical vector to select only those elements from my list, that fullfill my constraint (beeing over 6kg)
my_cats_over_6kg <- my_cats_names[which_one_is_over_6_kg_logical_vector]
my_cats_over_6kg
# > my_cats_over_6kg
# [1] "Boby" "Petzi"
# im pretty sure it was Boby or Petzi
# So by creating a logical vector we can select items from an existing vector if they fullfill our constraint
取而代之的是一个猫名向量,您得到一个数字向量,您可以计算其平均值和标准差。而不是选择超过 6 公斤的猫,您需要低于均值 (your_vector) - 2*sd(your_vector) 的数字和高于均值 (your_vector) + 2*sd(your_vector) 的数字。
我希望所有的猫都会有所帮助,而不是造成额外的混乱:)
推荐阅读
- java - io.realm.exceptions.RealmIOException: 无法打开 3
- elasticsearch - ElasticSearch - 如果文档不存在,部分更新是否会创建新文档?
- c# - SynFusion 错误:无法加载文件或程序集 Syncfusion.Pdf.Base,版本 = 16.4450.0.54
- python - pandas for循环导出文件包括所有条件
- hibernate - java.lang.NoClassDefFoundError 当我尝试启动我的服务器时
- javascript - Window.open 关闭时触发事件
- django - 如何使用 Django allauth 将 Linkedin 登录添加到我的网站?
- ssrs-2012 - 隐藏tablix时SSRS参数隐藏表达式错误
- javascript - 创建 Shopify 动态部分时出错
- ios - 使用 Swift 的 Location BLE GPS 解码 location_and_speed