简体   繁体   中英

How to isolate values in a dataframe based on a vector and multiply it by another column in the same dataframe using R?

I have a dataframe with multiple columns

col1|col2|col3|colA|colB|colC|Percent
  1     1    1    2    2    2     50

Earlier I subset the columns and created a vector

ColAlphabet<-c("ColA","ColB","ColC")

What i want to do is take ColAlphabet and multiply it by Percent so in the end I have

col1|col2|col3|colA|colB|colC|Percent
  1    1    1     1    1    1      50

We can use mutate with across . Specify the columns of interest wrapped with all_of and multiply the columns with 'Percent'

library(dplyr)
df2 <- df1 %>%
     mutate(across(all_of(ColAlphabet), ~ .* Percent/100))

-output

df2
#  col1 col2 col3 colA colB colC Percent
#1    1    1    1    1    1    1      50

data

df1 <- structure(list(col1 = 1L, col2 = 1L, col3 = 1L, colA = 2L, colB = 2L, 
    colC = 2L, Percent = 50L), class = "data.frame", row.names = c(NA, 
-1L))

You can subset the column, multiply with Percent and save it in ColAlphabet again.

ColAlphabet<-c("colA","colB","colC")
df[ColAlphabet] <- df[ColAlphabet] * df$Percent/100
df

#  col1 col2 col3 colA colB colC Percent
#1    1    1    1    1    1    1      50

We can also use apply() :

#Vector
ColAlphabet<-c("colA","colB","colC")
#Code
df[,ColAlphabet] <- apply(df[,ColAlphabet],2,function(x) x*df$Percent/100)

Output:

df
  col1 col2 col3 colA colB colC Percent
1    1    1    1    1    1    1      50

Some data used:

#Data
df <- structure(list(col1 = 1L, col2 = 1L, col3 = 1L, colA = 2L, colB = 2L, 
    colC = 2L, Percent = 50L), class = "data.frame", row.names = c(NA, 
-1L))

In case if you want to multiply directly:

> df <- data.frame(col1 = 1, col2 = 1, col3 = 1, colA = 2, colB = 2, colC = 2, Percent = 50)
> df
  col1 col2 col3 colA colB colC Percent
1    1    1    1    2    2    2      50
> df[grep('^c.*[A-Z]$', names(df))] <- df[grep('^c.*[A-Z]$', names(df))] * df$Percent/100
> df
  col1 col2 col3 colA colB colC Percent
1    1    1    1    1    1    1      50
> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM