【问题标题】:R data.table column that counts along unique values in other column [duplicate]R data.table 列沿其他列中的唯一值计数[重复]
【发布时间】:2018-04-13 03:04:35
【问题描述】:

我有一些长格式的数据想要加宽。 问题是数据的格式没有一条信息可以轻松传播。为了解决这个问题,我必须在数据框中创建一列,从 1 计数到另一列中每个唯一条目的长度。

在下面的过程中,是否有data.table的方式使列“fid”?

library(data.table)
library(tidyverse)

# data:
df <- data.frame(class = c('1', '1', '1', '2', '3', '3'),
                 A = 1:6,
                 B = 11:16)

# create counting column
df <- df %>% group_by(class) %>% mutate(fid=1:n())

# spread using dcast
dcast(setDT(df), class ~ fid, value.var = c("A", "B")) 

干杯

【问题讨论】:

  • 是的,rowid。在dcast 中使用class ~ rowid(class)

标签: r data.table tidyr


【解决方案1】:

另一种方法是使用data.table::rowid

df[,fid := rowid(class)]

【讨论】:

    【解决方案2】:

    data.table 创建列'fid'的方式,是将data.frame转换成data.tablesetDT(df)),按'class'分组,得到行序列(seq_len(.N))和将 (:=) 分配给 'fid'

    setDT(df)[, fid := seq_len(.N), class]
    

    但是,如果打算使用 dcast,则根本不需要创建列,因为有一个 rowid 函数可以直接在公式中使用,如 @mt1022 建议的那样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多