Useful R snippets

A collection of useful R snippets

Published
Published On
Last updated
Last Updated

library(tidyverse)

Create a new column with a value from a specific cell

Take the following simple data frame:

df <- tribble(
  ~x, ~y,
  "A", 0.1,
  "B", 0.4,
  "C", 0.2,
  "D", 0.3,
  "E", 0.5
)

df
xy
A0.1
B0.4
C0.2
D0.3
E0.5

Using the following code, we can add a new column that repeats a specific value from column y based on a value in a column x.

df <- mutate(df, z = nth(y, which(x == "B")))
df
xyz
A0.10.4
B0.40.4
C0.20.4
D0.30.4
E0.50.4

This can be useful if you want to do scaling based on specific values.

df |>
  mutate(y_scaled = y / z)
xyzy_scaled
A0.10.40.25
B0.40.41.00
C0.20.40.50
D0.30.40.75
E0.50.41.25