【问题标题】:Selections based on vector elements基于向量元素的选择
【发布时间】:2019-05-10 23:13:56
【问题描述】:

我非常新,提前抱歉。我有两个向量,一个是帐户名称的字符向量(30),另一个是产品名称的字符向量(30)。最后,我有一个包含三列帐户名称、产品名称和收入的数据框,但这个列表远远超出了其中的 30 个。

最终,我需要一个 30x30 的数据框行作为产品名称向量中的产品,列作为帐户名称向量中的帐户名称,并将值作为与列中的帐户和行中的产品相关联的收入。

我想我需要一个嵌套循环函数?但我不知道如何使用它来适当地填充数据框。

account<-c("a","b",etc)

product<-c("prod_a","prod_b", etc)

for(i in 1:length(account)){

    for(i in 1:length(product)){

.....
}
}

老实说,我只是很迷茫哈哈

【问题讨论】:

  • 不清楚你想要什么。如果您可以展示一个具有预期输出的小型可重现示例,那将很有用

标签: r dataframe


【解决方案1】:

认为我知道你想在这里做什么。我怀疑您想要这种 30x30 跨表类型的结构是有充分理由的,但我也想借此机会鼓励 "tidy" data 进行分析。该链接可以通过以下三个主要标准来概括,以使数据被视为“整洁”:

  1. 每个变量构成一列。

  2. 每个观察形成一行。

  3. 每种类型的观察单元形成一个表格。

也就是说,下面是我试图解释和展示我认为你想要完成的事情。

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

【讨论】:

  • 工作出色!我知道 %>% 管道,但我不知道 %in% 让事情变得如此简单哈哈。另外,是的,我知道我们应该使用整洁的数据,但这是远高于我的工资等级的销售人员的最终输出,他必须以这种方式进行报告。我只是不想手动这样做,所以这很有帮助。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 2011-02-03
  • 2012-10-30
  • 1970-01-01
  • 2023-04-03
  • 2018-05-10
相关资源
最近更新 更多