【问题标题】:Formula inside Mutate and use of ~变异里面的公式和使用~
【发布时间】:2021-08-10 08:36:33
【问题描述】:

假设我有一个数据框 df

df = data.frame(col1 = c(1:5),col2 = c(2:6))

我想通过将每个值加 10 来转换 col1。

我找到了几种方法,例如使用 recode 函数

df %>% mutate(col1 = recode(col1, "1" = "11", "2"="12", "3"="13", "4"="14", "5"="15"))

或使用mutate(across()) 函数。 df %>% mutate(across(col1, ~.x +10)

所以这是我的问题:

  1. x 和 . 的含义是什么?为了 ?我猜这意味着 col1 的每一行取 x 并加 10 ?

  2. 有什么方法可以更简单地进行这种转换?

谢谢

【问题讨论】:

  • 一栏不需要across,可以df %>% mutate(col1 = col1 + 10)
  • 谢谢!我对这个功能太着迷了,以至于忘记了基础。
  • 这是另一个可能对您有所帮助的链接:stackoverflow.com/questions/68249625/…

标签: r dplyr


【解决方案1】:

在这种情况下,您不需要across,因为它仅用于一列。

library(dplyr)

df %>% mutate(col1 = col1 + 10)

#  col1 col2
#1   11    2
#2   12    3
#3   13    4
#4   14    5
#5   15    6

关于~.的信息可以在What is meaning of first tilde in purrr::mapIn map(), when is it necessary to use a tilde and a period. (~ and .)Tilde and dots in R找到

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2023-03-21
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多