Adding a date to a frame based on input

后端 未结 1 1029
离开以前
离开以前 2021-01-29 01:40

I have an input variable for a data set in R that assesses a list of tools. It looks as follows:

type <- as.integer(readline(prompt=\"Enter a Barcode: \"))
         


        
1条回答
  •  灰色年华
    2021-01-29 02:20

    I would have hoped you could generalize from the last question I answered - this is really similar. Let's work it through:

    # load sample data
    dd = read.table(text = "Barcode_Number, Date_Used
    5698, 2018-07-07
    4570, 2018-07-11", header = TRUE, sep = ",")
    
    # make sure the date columns is Date class
    dd$Date_Used = as.Date(dd$Date_Used)
    
    # get barcode to update
    barcode_update <- as.integer(readline(prompt="Enter a Barcode: "))
    
    # make the update
    dd[dd$Barcode_Number == barcode_update, "Date_Used"] = Sys.Date()
    

    Now let's compare to your last question, where you wanted to update the column named "Times.Used". We'll pretend we're using the same variable name, barcode_update to hold the user input:

    dd[dd$Barcode_Number == barcode_update, "Date_Used"]  = Sys.Date()
    dd[dd$Barcode_Number == barcode_update, "Times.Used"] = df[df$Barcode_Number == tool, "Times.Used"] + 0.5
    

    The left hand sides of the assignment are identical, of the form,

    dd[dd$Barcode_Number == barcode_update, "Name of column to update"] = ......
    

    Data frame are referenced with brackets using data_name[rows, columns]. In both of these cases, we want to update certain rows: the rows where the barcode number matches the user input. So we do that test: dd[dd$Barcode_Number == barcode_update, ]. You could update the 3rd row with dd[3, ], the 1st, 2nd, and 5th rows with dd[c(1, 2, 5), ], or use some really complicated condition, maybe all the barcodes that have 0 in them dd[grepl("0", dd$Barcode_Number), ].

    In the column argument of [, we just need the name of the column to update, in quotes. Nice and simple. You could even use a variable there, that has the column name stored in it.

    The right hand side gets the new value. This question is simple - you want the new value to be the date returned by Sys.Date, so we do = Sys.Date() (or <- Sys.Date(), whichever you prefer). In the previous question, you wanted to add 0.5 to the existing "Times_Used" column, so we put the exact same thing on the right as on the left, but with a + 0.5 tacked on.

    0 讨论(0)
提交回复
热议问题