Search code examples
rmultiple-columnsaddition

Add value of 1 to multiple columns at the same time


I am a new user in R, and I have a dataset with 5000 variables. I am looking to add 1 for every 100 numerical variables, but I am not sure how I can determine these variables out of the huge dataset or what the formula could be. Just to make it clearer, the variable names that I want to add 1 for each one of them range from B-ARP, so I want to make something like this: B-ARP + 1. Perhaps this is a simple question, but I just started using R yesterday because I was using Stata.

I found this code bellow from another question but I am not sure if it is apply to my situation. library(dplyr) df %>% mutate(across(


Solution

  • Consider this data frame and say, we want to add 999 to columns X4 to X7.

    dat
    #   X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
    # 1  0  0  0  0  0  0  0  0  0   0
    # 2  0  0  0  0  0  0  0  0  0   0
    # 3  0  0  0  0  0  0  0  0  0   0
    # 4  0  0  0  0  0  0  0  0  0   0
    # 5  0  0  0  0  0  0  0  0  0   0
    

    First, we could identify which columns have those names,

    rg <- which(names(dat) %in% c('X4', 'X7'))
    rg
    # [1] 4 7
    

    and make a numerical sequence out of it.

    cols <- seq.int(rg[1], rg[2])
    cols
    # [1] 4 5 6 7
    

    (Alternatively using do.call:)

    cols <- do.call(seq.int, as.list(rg))
    ## or altogether:
    cols <- do.call(seq.int, as.list(which(names(dat) %in% c('X4', 'X7'))))
    

    Then just add 999 to subset dat[cols].

    dat[cols] <- dat[cols] + 999
    dat
    #   X1 X2 X3  X4  X5  X6  X7 X8 X9 X10
    # 1  0  0  0 999 999 999 999  0  0   0
    # 2  0  0  0 999 999 999 999  0  0   0
    # 3  0  0  0 999 999 999 999  0  0   0
    # 4  0  0  0 999 999 999 999  0  0   0
    # 5  0  0  0 999 999 999 999  0  0   0
    

    Data:

    dat <- data.frame(matrix(0, 5, 10))