答案 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