你可以在Dyplr的`rename_with()`函数的`.cols`参数中指定tibble的最后一列吗?

huangapple go评论95阅读模式
英文:

How can I specify the last column of a tibble within the rename_with() function's ".cols" argumnt in Dyplr?

问题

给定一个名为 "cars" 的 tibble:

  1. cars |>
  2. rename_with(~paste0(.x, ")"), .cols = (2:10))

上述代码在 tibble 的第2到第10列的列名后追加一个括号。如何从第二列到最后一列进行选择呢?你可以使用以下方法:

  1. rename_with(~paste0(.x, ")"), .cols = (2:ncol(betterLifeIndicators)))

但我确信 dyplr 包内一定有更加优雅的方法。我还想知道是否有一种方法可以选择除第一列(或任何其他指定的列集)之外的所有列。

提前谢谢!

英文:

Given a tibble "cars"

  1. cars |>
  2. rename_with(~paste0(.x, ")"), .cols = (2:10))

appends a parenthesis to the names columns 2 to 10 of the tibble. How would one go about selecting from the second to the last column? I have accomplished it with

  1. rename_with(~paste0(.x, ")"), .cols = (2:ncol(betterLifeIndicators)))

but I am sure there must be a more elegant way to do it within the dyplr package. I was also wondering if there is a way to select all columns except the first (or any other specified set).

Thank you in advance!

答案1

得分: 2

让我知道这是否有效。

  1. # 最后一列
  2. cars |>
  3. rename_with(~paste0(.x, ")"), .cols = last_col())
  4. # 倒数第二列
  5. cars |>
  6. rename_with(~paste0(.x, ")"), .cols = 2:last_col())
  7. # 除了第一列之外的所有列(与上面相同)
  8. cars |>
  9. rename_with(~paste0(.x, ")"), .cols = -1)
英文:

Let me know if this works.

  1. # Last column
  2. cars |>
  3. rename_with(~paste0(.x, ")"), .cols = last_col())
  4. # 2nd to Last column
  5. cars |>
  6. rename_with(~paste0(.x, ")"), .cols = 2:last_col())
  7. # All but first (same as above)
  8. cars |>
  9. rename_with(~paste0(.x, ")"), .cols = -1)

huangapple
  • 本文由 发表于 2023年4月7日 03:01:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952902.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定