循环添加到列中的值以生成新列

发布于 2025-01-09 07:39:16 字数 205 浏览 1 评论 0原文

我正在尝试创建某种循环来生成未来几年(以月为单位)的年龄百分比。我有两列,年龄和期限。将它们相除可以得到我正在寻找的百分比,但我需要一种简单的方法来将年龄加 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

想你只要分分秒秒 2025-01-16 07:39:16
library(tidyverse)

# create example data frame
df <- tribble(~age, ~term,
              10,   5,
              12,   6)

# create function to add new column 
agePlusN <- function(df, n) {
  mutate(df, "col.{n}" := term/(age+ n))
}

# iterate through 1:30 applying agePlusN() 
walk(1:30, \(n) df <<- agePlusN(df, n))

这可行,但最后一步有点难看。它确实应该使用地图而不是步行,但我不太清楚如何让它不添加新行。

尝试 2

# create function to add new column 
agePlusN <- function(df, n) {
  mutate(df, "col.{n}" := term/(age+n)) %>% 
  select(-term, -age)
}

# iterate through 1:30 applying agePlusN() 
df2 <- 
  map_dfc(1:30, \(n) agePlusN(df, n)) %>% 
  bind_cols(df, .)

注意:

  • mutate 中的 := 允许您在左侧参数的名称中使用 glue() 语法(例如"col.{n}")
  • map_dfc() 表示映射,然后使用 bind_cols 组合所有输出
  • \(n) 是等价的到function(n)
  • 调用 bind_cols() 中的 . 不是必需的,但可确保“age”和“term”列放在结果数据帧的开头。

我仍然认为这可以做得更好,而不必调用bind_cols,但我不够聪明,无法弄清楚。

library(tidyverse)

# create example data frame
df <- tribble(~age, ~term,
              10,   5,
              12,   6)

# create function to add new column 
agePlusN <- function(df, n) {
  mutate(df, "col.{n}" := term/(age+ n))
}

# iterate through 1:30 applying agePlusN() 
walk(1:30, \(n) df <<- agePlusN(df, n))

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

# create function to add new column 
agePlusN <- function(df, n) {
  mutate(df, "col.{n}" := term/(age+n)) %>% 
  select(-term, -age)
}

# iterate through 1:30 applying agePlusN() 
df2 <- 
  map_dfc(1:30, \(n) agePlusN(df, n)) %>% 
  bind_cols(df, .)

Notes:

  • The := in mutate allows you to use glue() 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 to function(n)
  • The . in the call to bind_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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文