I have a SpatialPointsDataFrame read via rgdal::readOGR

my_sp_layer <- readOGR(dsn="my_dsn", layer="my_layer_file")

# select rows using col_attrib column
my_sp_layer@data[my_sp_layer@data$col_attrib == 'some value',]  

How can I update the values of the selected rows?

If it is a data.table, I would just use

my_data_table[col_attrib == 'some value', col_to_update := 'new value']

1 Answer 1


First convert the column you want to amend to character as this will be set to factor by default:

shapefile@data$column_update <- as.character(shapefile@data$column_update)

Then just select the column you want to update with subset notation ([ ]) and use assign <-:

Shapefile@data$column_update[shapefile@data$column_condition == "condition"] <- " new_value"
  • I got NA's for the selected rows instead of a new value with the following warning message: In [<-.factor(*tmp*, Julita_more_hazard@data$Legend == "damaged culvert", : invalid factor level, NA generated Mar 7, 2016 at 9:07
  • @JunFolledo See edited answer. If this still doesn't solve it please provide a minimal reproducible example
    – Phil
    Mar 7, 2016 at 9:12
  • Thanks @Phil, it's now working after converting it to character, so I guest the readOGR must have been converted the character column as factor, am I right? Mar 7, 2016 at 9:18
  • @JunFolledo That's right, that's readOGR()'s default behaviour.
    – Phil
    Mar 7, 2016 at 9:18

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .