Я думаю Я знаю, что вы пытаетесь сделать здесь.Я подозреваю, что есть веская причина, по которой вы хотите использовать структуру с перекрестными таблицами 30x30, но я также хотел бы воспользоваться возможностью, чтобы поощрить «аккуратные» данные для целей анализа.Эту ссылку можно суммировать по этим трем основным критериям, чтобы данные считались «аккуратными»:
Каждая переменная образует столбец.
КаждыйНаблюдение образует ряд.
Каждый тип наблюдательной единицы формирует таблицу.
Тем не менее, ниже моя попытка интерпретировать и продемонстрировать, чтоЯ думаю, что вы пытаетесь достичь.
library(tidyr)
# set up some fake data to better explain
account_vec <- paste0(letters, 1:26)
product_vec <- paste0(as.character(101:126), LETTERS)
revenue_vec <- rnorm(26*26)
# permutating accounts and products to set up our fake data
df <- expand.grid(account_vec, product_vec)
names(df) <- c("accounts", "products")
df$revenue <- revenue_vec
# if this is what your data looks like currently, I would consider this fairly "tidy"
# now let's pretend there's some data we need to filter out
df <- rbind(df,
data.frame(
accounts = paste0("bad_account", 1:3),
products = paste0("bad_product", 1:3),
revenue = rnorm(3)
)
)
# filter to just what is included in our "accounts" and "products" vectors
df <- df[df$accounts %in% account_vec, ]
df <- df[df$products %in% product_vec, ]
# spread out the products so they occupy the column values
df2 <- df %>% tidyr::spread(key="products", value="revenue")
# if you aren't familiar with the "%>%" pipe operator, the above
# line of code is equivalent to this one below:
# df2 <- tidyr::spread(df, key="products", value="revenue")
# now we have accounts as rows, products as columns, and revenues at the intersection
# we can go one step further by making the accounts our row names if we want
row.names(df2) <- df2$accounts
df2$accounts <- NULL
# now the accounts are in the row name and not in a column on their own