0

I am trying to multiply a set of columns by another column in a data frame. While also keeping the column names unchanged. For example, I have a data frame dat:

Company_Name Company_Location Cost Fund_1  Fund_2 
A                 SGD          15         10     NA
B                 LDN          85         NA     4
C                 NY           54         3      NA
D                 SGD          15         NA     6
E                 LDN          85         4      5

dat <- structure(list(Company_Name = c("A", "B", "C", "D", "E"), Company_Location = c("SGD", 
LDN", "NY", "SGD", "LDN"), Cost = c(15L, 85L, 54L, 15L, 
85L), Fund_1 = c(10L, NA, 3L, NA, 4L), Fund_2 = c(NA, 4L, NA, 
6L, 5L)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", 
"data.frame"))

I would like to multiple the Cost column for both Fund_1 and Fund_2 and keep the names the same. i.e. no new columns. So the DF looks like the following;

Company_Name Company_Location Cost     Fund_1  Fund_2 
A                 SGD          15         150     NA
B                 LDN          85         NA     340
C                 NY           54         162     NA
D                 SGD          15         NA      90
E                 LDN          85         340     425

Any help is appreciated.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
CISCO
  • 539
  • 1
  • 4
  • 14

2 Answers2

1

You can do :

dat[4:5] <- dat$Cost * dat[4:5]

# A tibble: 5 x 5
#  Company_Name Company_Location  Cost Fund_1 Fund_2
#  <chr>        <chr>            <int>  <int>  <int>
#1 A            SGD                 15    150     NA
#2 B            LDN                 85     NA    340
#3 C            NY                  54    162     NA
#4 D            SGD                 15     NA     90
#5 E            LDN                 85    340    425

If you don't know the column numbers you can use grep to find out using their name pattern.

cols <- grep('Fund', names(dat))
dat[cols] <- dat$Cost * dat[cols]
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

If you're happy to use dplyr you can do this with mutate and across:

library(dplyr)

dat %>% mutate(across(c(Fund_1, Fund_2), ~ Cost * .))

# A tibble: 5 x 5
  Company_Name Company_Location  Cost Fund_1 Fund_2
  <chr>        <chr>            <int>  <int>  <int>
1 A            SGD                 15    150     NA
2 B            LDN                 85     NA    340
3 C            NY                  54    162     NA
4 D            SGD                 15     NA     90
5 E            LDN                 85    340    425

hamgamb
  • 11
  • 1