gpt4 book ai didi

r - 如何添加按顺序计算重复项的列?

转载 作者:行者123 更新时间:2023-12-01 03:34:24 26 4
gpt4 key购买 nike

我希望将一列添加到按顺序计算重复项的数据框 (integrates2) 中。下面是数据的样子:

name    program  date of contact   helper column
John ffp 10/11/2014 2
John TP 10/27/2014 2
Carlos TP 11/19/2015 3
Carlos ffp 12/1/2015 3
Carlos wfd 12/31/2015 3
Jen ffp 9/9/2014 2
Jen TP 9/30/2014 2

这是在特定日期参加过特定类(class)的人员列表。我添加了一个辅助列来计算重复项并对联系日期进行排序。我希望计算现有程序的组合(例如 ffp-tp、tp-ffp-wfd)。

为了做到这一点,我想实现以下代码,以便在名为“program2”的新列的帮助下转置有序组合:
 #transpose the programs 
require(reshape2) dcast(integrates2, name ~ program2, value.var=”program”)

然后我打算用下面的代码把结果转成表格和数据框并统计频率:
 res = table(integrates2)
resdf = as.data.frame(res)

我在以下链接中看到了这一点:
Count number of time combination of events appear in dataframe columns ext

我需要从“program2”中得到的是这样的:
  Name    program  date of contact   helper column   program2
John ffp 10/11/2014 2 1
John TP 10/27/2014 2 2
Carlos TP 11/19/2015 3 1
Carlos ffp 12/1/2015 3 2
Carlos wfd 12/31/2015 3 3

这样,我可以使用“program2”转置到不同的列中,然后计算组合。最终结果应该是这样的:
    program  pro1   pro2   freq      
ffp tp 2
TP ffp wfd 1

我确信有更简单的方法可以做到这一点,但在我学习的过程中,这就是我的所在。感谢帮助家伙!

最佳答案

在考虑了这个问题之后,我认为以下是要走的路。如果您不介意组合所有程序名称,您可以执行以下操作。这可能要好得多。

setDT(mydf)[, list(type = paste(program, collapse = "-")), by = name][,
list(total = .N), by = type]

# type total
#1: ffp-TP 2
#2: TP-ffp-wfd 1

如果你想分隔程序名称,你可以用 cSplit() 来做到这一点。来自 splitstackshape包裹。
setDT(mydf)[, list(type = paste(program, collapse = "-")), by = name][,
list(total = .N), by = type] -> temp

cSplit(temp, splitCols = "type", sep = "-")

# total type_1 type_2 type_3
#1: 2 ffp TP NA
#2: 1 TP ffp wfd

dplyr 代码的等价是:
group_by(mydf, name) %>%
summarise(type = paste(program, collapse = "-")) %>%
count(type)

# type n
# (chr) (int)
#1 ffp-TP 2
#2 TP-ffp-wfd 1

数据
mydf <- structure(list(name = c("John", "John", "Carlos", "Carlos", "Carlos", 
"Jen", "Jen"), program = c("ffp", "TP", "TP", "ffp", "wfd", "ffp",
"TP"), dateOfContact = c("10/11/2014", "10/27/2014", "11/19/2015",
"12/1/2015", "12/31/2015", "9/9/2014", "9/30/2014"), helperColumn = c(2L,
2L, 3L, 3L, 3L, 2L, 2L)), .Names = c("name", "program", "dateOfContact",
"helperColumn"), class = "data.frame", row.names = c(NA, -7L))

关于r - 如何添加按顺序计算重复项的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35977509/

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