【问题标题】:How to create specific number of columns dynamically based on a condition given a column in R如何根据给定R中的列的条件动态创建特定数量的列
【发布时间】:2018-09-01 17:58:55
【问题描述】:

我想根据 R 中给出的某些条件创建动态列数:

说,我有一个名为 x 的数据框:

Data Needed
   3

输出的 y 数据框应如下所示:

 Month_1    Month_2   Month_3
    10        13        25

如果输入数据框中的条目是:

Data Needed
   6

输出应如下所示:

   Month_1   Month_2    Month_3  Month_4    Month_5  Month_6
     10        13         25       18         11      29

我需要一些帮助,因为我是 R 新手。如果有人回复这个帖子会很棒。

【问题讨论】:

  • 至于列名,这很简单,paste0("Month_", seq_len(DataNeeded))。但是这些数字是从哪里来的呢?

标签: r dataframe


【解决方案1】:

请看下图:

create_df <- function(df, filler = c(10, 13, 25, 18, 11, 29)) {
  as.data.frame(matrix(filler[1:df$DataNeeded], nrow = 1, dimnames = list(NULL, paste0("Month_", 1:df$DataNeeded))))
}


df <- data.frame(DataNeeded = 3)
#      DataNeeded
# 1          3
create_df(df)
# Month_1 Month_2 Month_3
# 1      10      13      25

df <- data.frame(DataNeeded = 6)
create_df(df)
# Month_1 Month_2 Month_3 Month_4 Month_5 Month_6
# 1      10      13      25      18      11      29

但是,如果您要为DataNeeded > 6 调用create_df 函数,则需要手动提供filler 参数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 2020-03-07
    • 2018-07-01
    • 2020-07-13
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多