I have a dataset that looks as follows: enter image description here
I have two unique towns (Aurangabad and Munger) that have the same ID. How can I change the ID number for Munger to 193.
I have a dataset that looks as follows: enter image description here
I have two unique towns (Aurangabad and Munger) that have the same ID. How can I change the ID number for Munger to 193.
Select the row by using a comparison the name of the town you are looking for. Select the column by name. Assign a new value to the selected cell.
df[df$Town.name == "Town of Munger", "ID"] <- 193
Jan's answer is much more elegant than mine. However, my approach still gets the job done:
In the future, it's really best to provide data for us to work with, please do so. I recreated three lines or your data to show one way of doing this.
created data in R
df <- data.frame(Town.ID = c( "192", "192", "171"), Town.Name = c("Town of Aurangabad", "Town of Munger", "Town of Ara"))
Filter your data using the library(dplyr)
and the filter()
command
library(dplyr)
df_filter <- filter (df, Town.Name=="Town of Munger")
With the filtered data set, simply change the value(s) 192 to 193 in your Town.ID column (note: data needs to be considered as.factor()
for this to work
f_filter$Town.ID <- as.factor(df_filter$Town.ID)
levels(df_filter$Town.ID)[levels(df_filter$Town.ID)=="192"] <- "193"
Now we are going to combine this data set to the original one, however, in order to avoid having the "Town of Munger" listed twice (once from the old, and now from the new one), we need to first change it to "NA" in the original data set and delete it.
df$Town.Name <- as.factor(df$Town.Name)
levels(df$Town.Name)[levels(df$Town.Name)=="Town of Munger"] <- NA
# Remove NAs
new_df <- df[(!is.na(df$Town.Name)),]
Now combine the two using the smartbind()
command from library(gtools)
library(gtools)
Final_df <- smartbind(new_df,df_filter)
Voilà. Done