简体   繁体   English

R:使用 for 循环创建 1/n 权重的向量

[英]R: creating a vector of 1/n weights using a for loop

For the sake of making this general enough to be useful for others, I have six friends:为了使这个通用性足以对其他人有用,我有六个朋友:

friends <- c("luke", "leia", "han", "chewy", "lando", "obi")

That I am trying to give them each a portion of cake using a for loop我正在尝试使用 for 循环给他们每个人一份蛋糕

portions <- for (portion in length(friends)){
                 portion = 1/portion
}

My code returns the correct portion size (~16%), but does not populate my portions vector with what I was hoping for: (0.16,0.16,0.16,0.16,0.16,0.16)我的代码返回正确的部分大小(~16%),但没有用我希望的内容填充我的portions向量: (0.16,0.16,0.16,0.16,0.16,0.16)

Cutsie examples aside, I am looking to for a solution which can be applied to creating weights for several hundred variables.撇开 Cutsie 示例不谈,我正在寻找一种可以应用于为数百个变量创建权重的解决方案。

Any help would be greatly appreciated!任何帮助将不胜感激!

You could use你可以用

prop.table(table(friends))

#friends
#chewy   han lando  leia  luke   obi 
#0.167 0.167 0.167 0.167 0.167 0.167 

Or或者

table(friends)/length(friends)

We can just do rep on the 1/length(friends) and it would give the expected output without any other calculations我们可以只对1/length(friends)rep ,它会给出预期的输出,而无需任何其他计算

rep(1/length(friends), length(friends))
#[1] 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667

In the for loop, we are only assigning to portion each time and it gets updated.for循环中,我们每次只分配给portion并更新它。 Instead, an optioin is to pre-assign a vector and assign it to it相反,一个选项是预先分配一个向量并将其分配给它

portion <- numeric(length(friends))
for(i in seq_along(friends)) portion[i] <- 1/length(friends)
portion
#[1] 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM