[英]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我想要做的是将 ColAlphabet 乘以百分比,所以最后我有
col1|col2|col3|colA|colB|colC|Percent
1 1 1 1 1 1 50
We can use mutate
with across
.我们可以用mutate
与across
。 Specify the columns of interest wrapped with all_of
and multiply the columns with 'Percent'指定用all_of
包裹的感兴趣的列并将列乘以“百分比”
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
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.您可以对列进行子集化,乘以Percent
并将其再次保存在ColAlphabet
。
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()
:我们也可以使用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
>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.