fichtenelch.phd
fichtenelch.phd

Reputation: 3

How to replicate the values of a data frame in R with mutate( ..., ifelse())?

I'm struggling with a very basic issue. I need to extend an existing data frame with an extra row, which depends on the values of another Row - if said row has value "Machine 1" then a value based on an external script is added, if the value is not "Machine 1", then the new row should also just contain that name/value.

So far I have this:

mutate(df, new_row= ifelse(Machine_name=="Machine 1", "Value from external script", df$Machine_name))

Instead of the actual value of the "Machine_name" I get a different numeric value for each Machine but not the actual name.

Upvotes: 0

Views: 57

Answers (1)

Mark
Mark

Reputation: 12558

Here's a few different things you could mean:

library(dplyr)

df <- data.frame(Machine_name = paste("Machine", 1:3))

# add a new row for every machine, with the new name "blah" if the machine name is "Machine 1"
df |> add_row(df |> mutate(Machine_name = ifelse(Machine_name == "Machine 1", "blah", Machine_name)))

# only add a new row for Machine 1, with the new name "blah"
df |> add_row(df |> filter(Machine_name == "Machine 1") |> mutate(Machine_name = "blah"))

# just replace the name of Machine 1 with "blah"
df |> mutate(Machine_name = ifelse(Machine_name == "Machine 1", "blah", Machine_name))

Upvotes: 0

Related Questions