Rosette
Rosette

Reputation: 45

Referring to the same table while working in R

I'm currently working on a dataframe requiring some alterations in many columns. My code looks similar to this:

Table_A$Field_A <- "10"
Table_A$Field_B <- "20"
Table_A$Field_C <- "30"
Table_A$Field_D <- "20"
Table_A$Field_E <- "20"

It could be seen that it's repetitive. I think there should be a function or package that I can use to avoid typing Table_A$Field_X every time I work on different columns in the same dataframe.

I tried searching but I couldn't come up with the proper keyword to get the solution. All answer is appreciated. Thank you.

Upvotes: 2

Views: 57

Answers (1)

Konrad
Konrad

Reputation: 18585

Before using external packages have a look base::within function. The function allows you to specify your data frame as data argument and undertake modification on variables using expr argument that takes an expression.

TableA <-
    as.data.frame(sapply(
        X = paste("Field", LETTERS[1:5], sep = "_"),
        FUN = function(x) {
            3
        }, simplify = FALSE
    ))

within(data = TableA,
       expr = {
           Field_A = 1e3
           Field_B = -10
       }) -> TableA

Notes on comments

Please note that syntax for transform is different. To achieve the provided solution using transform you would do:

transform(TableA,
          Field_A = 1e3,
          Field_B = -10) -> Table_res_transform

This would be equivalent of:

within(data = TableA,
       expr = {
           Field_A = 1e3
           Field_B = -10
       }) -> Table_res_within

identical(Table_res_transform, Table_res_within)
# [1] TRUE

dplyr

require(dplyr)
TableA %>%
    mutate(Field_A = 1e3,
           Field_B = -10)

Upvotes: 1

Related Questions