第一个和最后一个变量的平均值

时间:2019-02-18 20:54:04

标签: r

Sample Data

突出显示的颜色是每个客户ID的第一个和最后一个,我该如何使用R代码执行此操作,下面是预期的答案

Answer expected

1 个答案:

答案 0 :(得分:0)

library(tidyverse)
df <- structure(list(Cus_ID = c(1, 2, 3), Sales1 = c(23.1, NA, NA), 
    Sales2 = c(NA, 14.2, NA), Sales3 = c(NA, NA, NA), Sales4 = c(NA, 
    21, 26), Sales5 = c(33, NA, 55), Sales6 = c(NA, NA, NA), 
    Sales7 = c(NA, NA, 11), Sales8 = c(NA, 23, 76), Sales9 = c(NA, 
    NA, NA), Sales10 = c(11, NA, NA)), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame"))

df %>%
  group_by(Cus_ID) %>%
  gather(sale_number, value, -Cus_ID) %>%
  filter(!is.na(value)) %>%
  summarise(avg_first_and_last = mean(c(first(value), last(value)))) %>%
  as.data.frame()
#   Cus_ID avg_first_and_last
# 1      1              17.05
# 2      2              18.60
# 3      3              51.00