gpt4 book ai didi

r - %>% 运算符中的 dplyr 重复

转载 作者:行者123 更新时间:2023-12-04 11:22:57 27 4
gpt4 key购买 nike

我正在尝试将 repdplyr 一起使用,但我不完全理解为什么我不能让它工作。

我的数据如下所示。我想要的是通过 n 为每个 id 简单地重复 dayweek

head(dt4)

id dayweek n
1 1 Friday 3
2 1 Monday 3
3 1 Saturday 3
4 1 Sunday 3
5 1 Thursday 3
6 1 Tuesday 3

我要做的是在 dplyr 流程中这样做

cbind(rep(dt4$id, dt4$n), rep(as.character(dt4$dayweek), dt4$n) ) 

这给了

    [,1] [,2]    
[1,] "1" "Friday"
[2,] "1" "Friday"
[3,] "1" "Friday"
[4,] "1" "Monday"
[5,] "1" "Monday"
[6,] "1" "Monday"

我不明白为什么这段代码不起作用

dt4 %>% 
group_by(id) %>%
summarise(rep(dayweek, n))

Error: expecting a single value

有人可以帮我解决这个问题吗?

数据

dt4 = structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), dayweek = structure(c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L,
4L, 5L, 6L, 7L), .Label = c("Friday", "Monday", "Saturday", "Sunday",
"Thursday", "Tuesday", "Wedesnday"), class = "factor"), n = c(3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3)), class = "data.frame", .Names = c("id",
"dayweek", "n"), row.names = c(NA, -21L))

最佳答案

data.table可以作为这种类型的操作操作的有用替代方案 - 我发现这更容易阅读:

library("data.table")
dt4 <- as.data.table(dt4)
head(dt4[, rep(dayweek, n), by=id], 10)

给予:

    id       V1
1: 1 Friday
2: 1 Friday
3: 1 Friday
4: 1 Monday
5: 1 Monday
6: 1 Monday
7: 1 Saturday
8: 1 Saturday
9: 1 Saturday
10: 1 Sunday

关于r - %>% 运算符中的 dplyr 重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32166852/

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