繁体   English   中英

基于字符在数据帧中乘以单元格

[英]Multiply cell in dataframe based on character

对于每个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))

使用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

基础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 

使用

df %>% 
  mutate(Value = Value * (grepl("2x", Product) + 1L))

首先为这些条目创建一个不同的列,使其具有2x,然后检查具有2x值的列并更新值列

df<-mutate(df, x=strsplit(Product, split = " ")[[1]][2])
df$Value[df$x=="2x"]<-2*df$Value[df$x=="2x"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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