user438383
user438383

Reputation: 6206

adding a new column based upon values in another column using dplyr

I have a column of a data frame df$c_touch:

c_touch
0
1
3
2
3
4
5

Where each number refers to a duration of time, such that 0 = 2 mins, 1 = 5 mins, 2 = 10 mins, 3=15 mins, 4=20 mins, 5=30 mins.

I'd like to add another column df$c_duration to be like

c_touch c_duration
0 2
1 5
3 15
2 10
3 15
4 20
5 30

So far I've been using a loop, which is a bit ugly/messy, and I'd rather not use it. Is there a loop-free way of adding the extra column in, particularly using dplyr mutate function (as I'm trying to rewrite all my code using dplyr)?

Upvotes: 2

Views: 11836

Answers (3)

Vinícius Félix
Vinícius Félix

Reputation: 8811

library(dplyr)

df %>%
  mutate(
    c_duration = case_when(
      c_touch == 0 ~ 2,
      c_touch == 5 ~ 30,
      TRUE ~ c_touch * 5
    )
  )

Upvotes: 7

Hearkz
Hearkz

Reputation: 109

You could use dplyr::case_when inside mutate:

df <- df %>%
    mutate(c_duration = case_when(c_touch == 0 ~ 2,
        c_touch == 1 ~ 5,
        c_touch == 2 ~ 10,
        c_touch == 3 ~ 15,
        c_touch == 4 ~ 20,
        c_touch == 5 ~ 30))

Upvotes: 0

Maurits Evers
Maurits Evers

Reputation: 50668

Here is a dplyr solution:

# data.frame containing the mapping
map <- data.frame(
    idx = 0:5,
    val = c(2, 5, 10, 15, 20, 30))

# Sample data   
df <- read.table(text =
    "c_touch
0
1
3
2
3
4
5", header = T)

dplyr::left_join(df, map, by = c("c_touch" = "idx"))
#  c_touch val
#1       0   2
#2       1   5
#3       3  15
#4       2  10
#5       3  15
#6       4  20
#7       5  30

Upvotes: 2

Related Questions