Home > Back-end >  Update single row of data frame in R
Update single row of data frame in R

Time:04-14

my dataframe:

Name Value
Setosa 1
Versicolor 2

So first of all, I want to check if an input matches the name in any row.

My solution for the filter so far:

# input$df <- Versicolor

import dplyr
df_table <- df_table %>%
      dplyr::filter(grepl(input$df, Name, ignore.case = TRUE))

If there is a match, I'd like to update/overwrite this row with new values, like in the following table:

Name Value
Setosa 1
Versicolor 3

The name stays the same, but only the value changes.

Do you have any advice?

CodePudding user response:

You can try the following:

df_table[df_table$Name == input$df, 'Value'] <- new_value

This will update the Value column for all rows where the value in Name is the same as input$df which in your example is Versicolor

CodePudding user response:

We can use a join

library(dplyr)
df_table %>%
    left_join(input, by = c("Name")) %>%
    mutate(Value = coalesce(Value.x, Value.x), .keep = "unused")

Or with data.table

library(data.table)
setDT(df_table)[input, Value := i.Value, on = .(Name)]
  •  Tags:  
  • r
  • Related