对于每个有2x的乘积,如何将值乘以因子2?
Restaurant Product Value
1 a 3
1 b 2x 5
2 c 10
2 a 2x 2
我试过了:
df = df %>%
mutate(Value=case_when(
Product =="2x"~ Value * 2,T~1))
两个基本R选项:
# option 1:
df$Value <- df$Value * (grepl("2x", df$Product) + 1L)
# option 2:
ix <- grepl("2x", df$Product)
df$Value[ix] <- df$Value[ix] * 2L
它给出:
> df Restaurant Product Value 1 1 a 3 2 1 b 2x 10 3 2 c 10 4 2 a 2x 4
带dplyr:
df %>%
mutate(Value = Value * (grepl("2x", Product) + 1L))
使用tidyverse,只需执行:
df %>% mutate(x=(1+str_detect(Product,"2x"))*Value)
# Restaurant Product Value x
#1 1 a 3 3
#2 1 b 2x 5 10
#3 2 c 10 10
#4 2 a 2x 2 4
首先为具有2x值的条目创建一个不同的列,然后检查具有2x的值的列,并更新相同的值列
df<-mutate(df, x=strsplit(Product, split = " ")[[1]][2])
df$Value[df$x=="2x"]<-2*df$Value[df$x=="2x"]