为了使这个通用性对其他人有用,我有六个朋友:
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示例,我正在寻找一种可以应用于为数百个变量创建权重的解决方案。
任何帮助将不胜感激!
您可以使用
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)
我们可以只在rep
上执行1/length(friends)
rep(1/length(friends), length(friends))
#[1] 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667