循环添加到列中的值以生成新列
我正在尝试创建某种循环来生成未来几年(以月为单位)的年龄百分比。我有两列,年龄和期限。将它们相除可以得到我正在寻找的百分比,但我需要一种简单的方法来将年龄加 1,并保持术语一致,并使用它来创建一个新列。类似于:
for i = n
col_n<-data_set$term/(data_set$age + n)
n=30
I'm trying to create some sort of loop to generate a % of age over the next few years, in months. I have two columns, age and term. Dividing them gets me the % I'm looking for, but I need an easy way to add 1 to age, and keep term consistent, and use that to create a new column. Something like:
for i = n
col_n<-data_set$term/(data_set$age + n)
n=30
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可行,但最后一步有点难看。它确实应该使用地图而不是步行,但我不太清楚如何让它不添加新行。
尝试 2
注意:
:=
允许您在左侧参数的名称中使用glue()
语法(例如"col.{n}"
)map_dfc()
表示映射,然后使用 bind_cols 组合所有输出\(n)
是等价的到function(n)
bind_cols()
中的.
不是必需的,但可确保“age”和“term”列放在结果数据帧的开头。我仍然认为这可以做得更好,而不必调用bind_cols,但我不够聪明,无法弄清楚。
This works, but the last step is a bit ugly. It should really use map instead of walk, but I couldn't quite figure out how to get it not to add new rows.
Attempt 2
Notes:
:=
in mutate allows you to useglue()
syntax in the names on the left hand side argument (eg."col.{n}"
)map_dfc()
means map and then use bind_cols to combine all of the outputs\(n)
is equivalent tofunction(n)
.
in the call tobind_cols()
isn't necessary but makes sure the 'age' and 'term' columns are put at the beginning of the resulting dataframe.I still think this could be done better without having to call bind_cols, but I'm not smart enough to figure it out.