0

How would I go about setting a conditional mutate on a column, but preserving the original content.

For example, consider:

DF=data.frame(A=1:10, B=c("fail1", "fail2", rep(NA,8)))

DF=DF %>% mutate(B = ifelse(A<4,paste(B, "less than 4"),B))

What I want is to produce the following:

DF_want=data.frame(A=1:10, B=c("fail1 less than 4", "fail2 less than 4", "less than 4", rep(NA,7)))

But because I am calling the column B directly, and not the specific row in B, this isn't happening.

sindri_baldur
  • 22,360
  • 2
  • 25
  • 48
sym246
  • 1,506
  • 2
  • 16
  • 41
  • @snoram That won't work; see my answer below – duckmayr Oct 03 '18 at 11:45
  • @duckmayr we are clearly reading different things into what the op is looking for. I though the key was `preserving the original content.` – sindri_baldur Oct 03 '18 at 11:46
  • @snoram That's what I thought at first too from reading the text of the question (it's the most natural reading of just the text part), but the problem becomes clear when you run the code they posted and look at the expected output posted. – duckmayr Oct 03 '18 at 11:47

2 Answers2

3

The only difference I see between your expected output and the actual output is that the third entry of B, which is NA less than 4 rather than less than 4. This is because of how paste() works; consider the following:

paste(NA, "a")
# [1] "NA a"

So, instead do this:

DF %>% mutate(B = sub("NA", "", ifelse(A < 4,paste(B, "less than 4"), B)))

    A                 B
1   1 fail1 less than 4
2   2 fail2 less than 4
3   3       less than 4
4   4              <NA>
5   5              <NA>
6   6              <NA>
7   7              <NA>
8   8              <NA>
9   9              <NA>
10 10              <NA>
duckmayr
  • 14,919
  • 2
  • 28
  • 44
2

A different possibility:

DF %>%
  mutate(B = ifelse(A < 4 & !is.na(B), paste(B, "less than 4"), 
                    ifelse(A < 4 & is.na(B), paste("less than 4"), B))) 

    A                 B
1   1 fail1 less than 4
2   2 fail2 less than 4
3   3       less than 4
4   4              <NA>
5   5              <NA>
6   6              <NA>
7   7              <NA>
8   8              <NA>
9   9              <NA>
10 10              <NA>
tmfmnk
  • 31,986
  • 3
  • 26
  • 41