checkmate363
checkmate363

Reputation: 49

Rename values based on a filter

I have a set of data with three values: Germany, Federal Republic Of Germany, and German Democratic Republic as the values inside the column . I have another column called Effect that is a date class. I want to rename the Country value from Germany to Federal Republic Of Germany for all values where Effect > 1990.

I've tried the following code and it has not worked

clean.data$Country <- clean.data %>% filter(Country == "Germany" & Effect > 1990) %>% rename(Federal Republic Of Germany = Germany) #Method 1
clean.data$Country <- clean.data %>% filter(Country == "Germany" & Effect > 1990) %>% rename("Federal Republic Of Germany" = "Germany") #Method 2

I also can't seem to find the command to pull the row numbers that meet the filter. If I could, I would do

rownumbers <- #Command to find row numbers
clean.data$Country[rownumbers] <- "Federal Republic Of Germany"

What other methods are there to change the observation? Or am I doing something wrong in the above dplyr chain?

Upvotes: 1

Views: 1362

Answers (2)

akrun
akrun

Reputation: 887511

The assignment should be to the same object or different object and not a column as the output from rename is still a data.frame and rename is for renaming the column and not the value

library(dplyr)
clean.data1 <-  clean.data %>%
   filter(Country == "Germany" & Effect > 1990) %>%
   rename(`Federal Republic Of Germany` = "Germany")

If we want to change the value, then do

clean.data %>%
   mutate(Country = case_when(Country == "Germany" & Effect > 1990 ~ "Federal Republic Of Germany", TRUE ~ Country))

In base R, we can use an index if we need to change the values of the 'Country' column

i1 <- with(clean.data, Country == "Germany" & Effect > 1990)
clean.data$Country[i1] <- "Federal Republic Of Germany"

Upvotes: 3

Duck
Duck

Reputation: 39613

In base R this can work:

#Code
rownumbers <- which(clean.data$Country == "Germany" & clean.data$Effect > 1990)
clean.data$Country[rownumbers] <- "Federal Republic Of Germany"

Upvotes: 0

Related Questions