Skip to content

tidyverse 版本(dplyr不完全不够用)代码前三题代码优化建议 #12

@chuxinyuan

Description

@chuxinyuan
```{r}
#| warning: false
#| message: false
library(dplyr)
library(stringr)
stack_data = readRDS("./data/stock-market-data.rds")
data = as_tibble(stack_data)
```

# 哪些股票的代码中包含 “8” 这个数字?

```{r}
data %>% 
  filter(str_detect(symbol, "8")) %>% 
  distinct(symbol)
```

# 每天上涨和下跌的股票各有多少?

```{r}
data %>% 
  summarise(
    UP = sum(close > pre_close),
    DOWN = sum(close < pre_close),
    STEADY = sum(near(close, pre_close)),
    .by = date
  )
```

# 每天每个交易所上涨、下跌的股票各有多少?

```{r}
data %>% 
  mutate(exchange = str_sub(symbol, -2, -1)) %>% 
  # 显式指定分组变量结果会按照分组变量排序
  group_by(date, exchange) %>%  
  summarise(
    UP = sum(close > pre_close),
    DOWN = sum(close < pre_close),
    STEADY = sum(near(close, pre_close)),
    .groups = "drop"
  )
```

以上代码主要参考了 @zhjx19 的解决方案,供参考。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions