Reputation: 15
Let's say I have a data frame df
df = data.frame(col1 = c(1:5),col2 = c(2:6))
I want to transform col1 by adding 10 to each value.
I have found several ways to do it for example using the recode
function
df %>% mutate(col1 = recode(col1, "1" = "11", "2"="12", "3"="13", "4"="14", "5"="15"))
or using mutate(across())
function.
df %>% mutate(across(col1, ~.x +10)
So here are my questions :
What are the meanings of x and the . for ? I guess it means for every row of col1 take x and add 10 ?
What could be an easier way to do this transformation ?
Thank you
Upvotes: 0
Views: 204
Reputation: 389135
In this case, you don't need across
since it is only for one column.
library(dplyr)
df %>% mutate(col1 = col1 + 10)
# col1 col2
#1 11 2
#2 12 3
#3 13 4
#4 14 5
#5 15 6
Information about ~
and .
can be found at What is meaning of first tilde in purrr::map , In map(), when is it necessary to use a tilde and a period. (~ and .) and Tilde and dots in R
Upvotes: 2