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

问题描述 投票:0回答:2

为了使这个通用性对其他人有用,我有六个朋友:

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

我正在尝试使用for循环给他们每个蛋糕的一部分

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

我的代码返回正确的部分大小(〜16%),但没有用我希望的内容填充我的portions向量:(0.16,0.16,0.16,0.16,0.16,0.16)

除了Cutsie示例,我正在寻找一种可以应用于为数百个变量创建权重的解决方案。

任何帮助将不胜感激!

r for-loop
2个回答
0
投票

您可以使用

prop.table(table(friends))

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

table(friends)/length(friends)

0
投票

我们可以只在rep上执行1/length(friends)

rep(1/length(friends), length(friends))
#[1] 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667
© www.soinside.com 2019 - 2024. All rights reserved.