gpt4 book ai didi

r - 按行计算列数,避免熔化/聚集

转载 作者:行者123 更新时间:2023-12-05 03:09:44 28 4
gpt4 key购买 nike

<分区>

我正在使用这样的数据框:

   idno      08:00      08:05      08:10    08:15    08:20    08:25
1 1 Domestic Domestic Domestic Domestic Domestic Domestic
2 2 Leisure Leisure Leisure Leisure Leisure Leisure
3 3 Eat Eat Eat Eat Eat Eat
4 4 Paid Paid Paid Paid Paid Paid
5 5 Sleep Sleep Sleep Sleep Sleep Sleep
6 6 Eat Eat Eat Missing Missing Missing
7 7 Sleep Sleep Sleep Sleep Sleep Sleep
8 8 Paid Paid Paid Paid Paid Paid
9 9 Sleep Sleep Sleep Sleep Sleep Sleep
10 10 Child Care Child Care Child Care Travel Travel Travel

我感兴趣的是像这样总结这个数据框。

(想要输出)

       idno `Child Care` Domestic   Eat Leisure Missing  Paid Sleep Travel
* <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 0 6 0 0 0 0 0 0
2 2 0 0 0 6 0 0 0 0
3 3 0 0 6 0 0 0 0 0
4 4 0 0 0 0 0 6 0 0
5 5 0 0 0 0 0 0 6 0
6 6 0 0 3 0 3 0 0 0
7 7 0 0 0 0 0 0 6 0
8 8 0 0 0 0 0 6 0 0
9 9 0 0 0 0 0 0 6 0
10 10 3 0 0 0 0 0 0 3

我通常做的就是这样:

melt(df, id.vars = 'idno') %>% count(idno, value) %>% spread(value, n, 0)

但是,我想知道是否有更直接的方法来做到这一点。我的问题是我正在使用一个非常大的数据库并使用 melt,然后是 count 然后是 spread 可能有点慢。

有没有一种直接的方法来计算每行的列(变量的分布),最好使用data.table

setDT(df)[,.N,by=] # 

像每行的 by 列一样?

df = structure(list(idno = 1:10, `08:00` = c("Domestic", "Leisure", 
"Eat", "Paid", "Sleep", "Eat", "Sleep", "Paid", "Sleep", "Child Care"
), `08:05` = c("Domestic", "Leisure", "Eat", "Paid", "Sleep",
"Eat", "Sleep", "Paid", "Sleep", "Child Care"), `08:10` = c("Domestic",
"Leisure", "Eat", "Paid", "Sleep", "Eat", "Sleep", "Paid", "Sleep",
"Child Care"), `08:15` = c("Domestic", "Leisure", "Eat", "Paid",
"Sleep", "Missing", "Sleep", "Paid", "Sleep", "Travel"), `08:20` = c("Domestic",
"Leisure", "Eat", "Paid", "Sleep", "Missing", "Sleep", "Paid",
"Sleep", "Travel"), `08:25` = c("Domestic", "Leisure", "Eat",
"Paid", "Sleep", "Missing", "Sleep", "Paid", "Sleep", "Travel"
)), .Names = c("idno", "08:00", "08:05", "08:10", "08:15", "08:20",
"08:25"), row.names = c(NA, 10L), class = "data.frame")

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com