Search code examples
rdataframereplacerowna

Replace column values with NA by index row position in r


My data frame looks like this:

points_U <- data.frame(
  Date = c(
    "2015-07-28", "2015-07-29", "2015-07-30", "2015-07-31", "2015-08-01",
    "2015-08-02", "2015-08-03", "2015-08-04", "2015-08-05", "2015-08-06",
    "2015-08-07", "2015-08-08", "2015-08-09", "2015-08-10", "2015-08-11",
    "2015-08-12", "2015-08-13", "2015-08-14", "2015-08-15", "2015-08-16"
  ),
  U_NDVI = c(
    0.241392907, 0.257591745, 0.263305712, NA, 0.252892547, 0.251771181,
    0.249211747, 0.257289083, 0.205017583, 0.200722746, 0.210154168, 0.207384553,
    0.193725451, 0.199282602, 0.216267134, 0.217052471, NA, 0.22070303,
    0.21646198, 0.223442036
  )
)

I'm trying to replace the numeric values of column U_NDVI with NA by index row position. The index row positions are 3, 6,9, 14, 19, and 20.

I tried this:

points_U$NDVI[3, 6,9, 14, 19, 20] <- NA

but no success.

Any help is much appreciated.


Solution

  • The correct way of doing it is to use square bracket ([row, column]) to index a dataframe.

    points_U[c(3, 6,9, 14, 19, 20), "U_NDVI"] <- NA
    
             Date    U_NDVI
    1  2015-07-28 0.2413929
    2  2015-07-29 0.2575917
    3  2015-07-30        NA
    4  2015-07-31        NA
    5  2015-08-01 0.2528925
    6  2015-08-02        NA
    7  2015-08-03 0.2492117
    8  2015-08-04 0.2572891
    9  2015-08-05        NA
    10 2015-08-06 0.2007227
    11 2015-08-07 0.2101542
    12 2015-08-08 0.2073846
    13 2015-08-09 0.1937255
    14 2015-08-10        NA
    15 2015-08-11 0.2162671
    16 2015-08-12 0.2170525
    17 2015-08-13        NA
    18 2015-08-14 0.2207030
    19 2015-08-15        NA
    20 2015-08-16        NA