-1

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.

  • Please read [this post](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on how to ask a good question in R. Particularly, please include a reproducible example by editing the output of ``dput(head(data))`` into your original question. This will help people trying to answer your question. Thanks. – user438383 Feb 08 '21 at 15:11

2 Answers2

1

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
  • 4,974
  • 3
  • 26
  • 43
  • well done. I was scratching my head on how to select two parameters, in this case, two columns, to target very specific data and to change it. So I did a whole fiasco in my response to get it done. But you taught me how to do this much better in the future. Thanks – Andy Feb 08 '21 at 15:58
0

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

Andy
  • 413
  • 2
  • 15