【问题标题】:Dataframe reshaping based on column count基于列数的数据框重塑
【发布时间】:2014-09-26 01:42:49
【问题描述】:

我有一个 2 列 100,000 行的数据框,如下所示:

Count               String
3                 "Hello World"
2                  "Hi John"
1                  "Dear Joe"

我想将此数据框重塑为 1 列数据框,删除计数并添加重复项。例如,

String 
"Hello World"
"Hello World"
"Hello World"
"Hi John"
"Hi John"
"Dear Joe"

【问题讨论】:

标签: r dataframe reshape reshape2


【解决方案1】:

试试

one_col_df <- data.frame(String = rep(df$String, df$Count))

对于每个字符串,函数rep 将重复Count 次,同时尊重它们在向量中的顺序。

【讨论】:

    【解决方案2】:

    这是一种方法。

    a <- c(3:1)
    foo <- c("hello", "hi", "dear")
    
    rep(foo, a)
    
    [1] "hello" "hello" "hello" "hi"    "hi"    "dear" 
    

    【讨论】:

      猜你喜欢
      • 2021-09-23
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 2011-03-29
      • 2021-06-05
      • 1970-01-01
      • 2019-10-08
      相关资源
      最近更新 更多