## 通过跟随R中单个变量中的数字乘以第一个数字内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (9)

``````juice <- c(101,204,310)
``````

### 2 个回答

``````> dat_3digits <- data.frame(drinks = c(104,  209 , 301))
>
> library(tidyverse)
> dat_3digits %>%
mutate(freq  = sub("\\d{2}\$", "", drinks)%>%  as.numeric,
times = sub("\\d{1}", "", drinks) %>%  as.numeric,
new_drinks = if_else(freq == 1, times * 7,
if_else(freq == 3, (times/30)*7, freq)))
drinks freq times new_drinks
1    104    1     4 28.0000000
2    209    2     9  2.0000000
3    301    3     1  0.2333333
``````

``````transform(transform(dat_3digits,
freq = as.numeric(substr(drinks, start=1, stop=1)),
drinks2 = as.numeric(substr(drinks, start=2, stop=3))),
new_drinks = ifelse(freq == 1, drinks2 * 7,
if_else(freq == 3, (drinks2/30)*7, freq)))
``````

``````df <- data.frame(juice = c(104, 106, 204, 209, 302, 332, 111))

c(7,1,7/30)[df\$juice %/% 100]  * df\$juice %% 100
#[1] 28.0000000 42.0000000  4.0000000  9.0000000  0.4666667  7.4666667 77.0000000
``````