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

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

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

问题

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

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

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

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

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

提前谢谢!

英文:

Given a tibble "cars"

cars |>
  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

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

让我知道这是否有效。

# 最后一列
cars |>
  rename_with(~paste0(.x, ")"), .cols = last_col())

# 倒数第二列
cars |>
  rename_with(~paste0(.x, ")"), .cols = 2:last_col())

# 除了第一列之外的所有列(与上面相同)
cars |>
  rename_with(~paste0(.x, ")"), .cols = -1)
英文:

Let me know if this works.

# Last column
cars |> 
  rename_with(~paste0(.x, ")"), .cols = last_col())

# 2nd to Last column
cars |> 
  rename_with(~paste0(.x, ")"), .cols = 2:last_col())

# All but first (same as above)
cars |> 
  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:

确定