ShixiangWang / self-study

My Self-Study Room: keep tidy and lightweight
https://shixiangwang.github.io/self-study/
30 stars 6 forks source link

函数循环求助 #28

Closed ShixiangWang closed 3 years ago

ShixiangWang commented 5 years ago

你好,我在"简书"上看到了你的apply函数的应用,我的数据是要每个公司(包括16个季度)按函数表达式计算一遍,不知道该怎么解决,向您求助以下,感谢!

ShixiangWang commented 5 years ago

你好,

这是一个关于分组计算的问题,可以使用 dplyr 包进行快速的解决。因为你提供的数据是图片,所以我自己生成了一个样例数据

# Load the required package
library(tidyverse)

# Read the data firstly
# Here I create a sample data
data = tibble(
  company = rep(LETTERS[1:4], each=4),
  year = rep(1:4, 4),
  value = 1:16
)

data

# What you need is group by some variables
# and summarize one or many values
# Let's say median and sum
data %>% 
  group_by(company) %>% 
  summarise(
    min_value = min(value),
    sum_value = sum(value)
  )

data %>% 
  group_by(year) %>% 
  summarise(
    min_value = min(value),
    sum_value = sum(value)
  )

# You can add more variables as you like
# and also summarize all values what you want
data %>% 
  group_by(company, year) %>% 
  summarise(
    min_value = min(value),
    sum_value = sum(value)
  )