【问题标题】:How to insert a name of list table into a column using R [closed]如何使用 R 将列表表的名称插入到列中 [关闭]
【发布时间】:2018-08-20 09:23:22
【问题描述】:

我有这样的数据:

# Data
varx1 <- data.frame(datex = c("2018/01/01","2018/01/02","2018/01/03"), x = c(101,102,103)) 
varx2 <- data.frame(datex = c("2018/01/01","2018/01/02","2018/01/03","2018/01/04","2018/01/05"), x = c(10,11,12,13,14))
varx3 <- data.frame(datex = c("2018/01/01"), x = c(1000))
combination <- list(`code status OK01` = varx1, `code trx OCS02` = varx2, `Revenue 101` = varx3)
combination

我想要这样的结果:

# Result
result <- data.frame(datex = c("2018/01/01","2018/01/02","2018/01/03","2018/01/01","2018/01/02","2018/01/03","2018/01/04","2018/01/05","2018/01/01"),
                 combination = c("code status OK01","code status OK01","code status OK01","code trx OCS02","code trx OCS02","code trx OCS02","code trx OCS02","code trx OCS02","Revenue 101"),
                 x = c(101,102,103,10,11,12,13,14,1000))
result

需要帮助解决这个问题。谢谢

【问题讨论】:

  • 您到底需要什么?你能提供更多细节吗?
  • 请阅读How to Ask。您的问题目前尚不清楚。
  • 您好,先生。你会运行脚本吗?我想使用列表中的数据框名称创建一个新列。谢谢
  • combination 在第一个代码块中包含什么?
  • 对不起代码,我已经更新了,谢谢之前

标签: r dplyr data.table reshape reshape2


【解决方案1】:

我不知道变量varx3,但这会起作用:

library(tidyverse)
result <- varx1 %>%
  mutate(combination="code status OK01") %>% 
  bind_rows(varx2 %>% 
              mutate(combination="code trx OCS02")) %>% 
  bind_rows(varx3 %>% 
              mutate(combination="Revenue 101")) %>% 
  select(datex, combination, x)
result

如果您想在列表中工作(假设列表是静态的):

library(tidyverse)
result <- combination[[1]] %>% 
  mutate(combination="code status OK01") %>% 
  bind_rows(combination[[2]] %>% 
              mutate(combination="code trx OCS02")) %>% 
  bind_rows(combination[[3]] %>% 
              mutate(combination="Revenue 101")) %>% 
  select(datex, combination, x)
result

您指出,您有 100 多个变量。因此,如果您有 combination 包含 100 个变量的数据框,每个变量都在一个大列表中的单个数据框中,您可以使用:

library(tidyverse)
var_names <- names(combination)
df <- NULL
for (i in 1:length(var_names)) {
  df[[i]] <- combination[[i]] %>%
    mutate(combinate=var_names[[i]])
}
result <- bind_rows(df)
result

【讨论】:

  • 你好..我的互联网很慢,所以每次我编辑它都不会保存它。但是,先生,你能让组合变量更通用吗?因为我有 100 件商品。谢谢
  • 更新了我的答案
  • 谢谢先生。它有效
猜你喜欢
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多