2

I have a SpatialPointsDataFrame read via rgdal::readOGR

require(rgdal)
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']
3

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 – Jun Folledo Mar 7 '16 at 9:07
  • @JunFolledo See edited answer. If this still doesn't solve it please provide a minimal reproducible example – Phil Mar 7 '16 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? – Jun Folledo Mar 7 '16 at 9:18
  • @JunFolledo That's right, that's readOGR()'s default behaviour. – Phil Mar 7 '16 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.