Reputation: 41
My attempt to add a new column to a dataframe with mutate gave me a tibble with the new variable, but did not add the variable as a new column in the dataframe (which is what I want to do).
I have a data frame with a character variable, DRUG_GENERIC_NAME
, and created a new logical variable, Ibuprofen
by combining mutate and str_detect which will be TRUE
when IBUPROFEN
is contained in DRUG_GENERIC_NAME
:
mutate(Drug_Table, DRUG_GENERIC_NAME, Ibuprofen = str_detect (Drug_Table$DRUG_GENERIC_NAME,"IBUPROFEN", negate = FALSE))
The result was a tibble with the new variable Ibuprofen, but the code did not add the variable to the data frame Drug_Table
. How can I use this code to add the new variable to the dataframe instead of creating a tibble?
Upvotes: 2
Views: 802
Reputation: 167
Just as Calum You proposed, You have to assign the result to the original data frame using the "<-" operator:
Drug_Table <- mutate(Drug_Table, DRUG_GENERIC_NAME, Ibuprofen = str_detect (Drug_Table$DRUG_GENERIC_NAME,"IBUPROFEN", negate = FALSE))
If You need the data frame to still be a data.frame (and not a tibble) use as.data.frame()
Drug_Table <- as.data.frame(mutate(Drug_Table, DRUG_GENERIC_NAME, Ibuprofen = str_detect (Drug_Table$DRUG_GENERIC_NAME,"IBUPROFEN", negate = FALSE)))
Upvotes: 0
Reputation: 887128
We can use the compound assignment operator (%<>%
) from magrittr
if we don't want to assign it back with <-
library(magrittr)
Drug_Table %<>%
mutate(Ibuprofen = str_detect(DRUG_GENERIC_NAME,"IBUPROFEN", negate = FALSE))
Upvotes: 1