gpt4 book ai didi

r - 更改 dcast 以显示多列

转载 作者:行者123 更新时间:2023-12-05 00:23:47 25 4
gpt4 key购买 nike

我有以下情况。考虑以下 df:

mymatrix <- as.data.frame(matrix(data = 0, nrow = 7, ncol = 4))
colnames(mymatrix) <- c("Patient", "marker", "Number", "Visit")

mymatrix[,1] <- c("B1","B1","C1","C1","D1","D1","D1")
mymatrix[,2] <- c("A","A","A","A","A","A","A")
mymatrix[,3] <- c(1,0,0,15,1,2,13)
mymatrix[,4] <- c("baseline","followup","baseline","followup","baseline","followup","followup")

> mymatrix
Patient marker Number Visit
1 B1 A 1 baseline
2 B1 A 0 followup
3 C1 A 0 baseline
4 C1 A 15 followup
5 D1 A 1 baseline
6 D1 A 2 followup
7 D1 A 13 followup

如果我在前 6 行做 dcast,我会得到:
> dcast(mymatrix[1:6,], Patient +marker~Visit, value.var = "Number")
Patient marker baseline followup
1 B1 A 1 0
2 C1 A 0 15
3 D1 A 1 2

如果我对我得到的所有行进行 dcast:
> dcast(mymatrix, Patient +marker~Visit, value.var = "Number")
Aggregation function missing: defaulting to length
Patient marker baseline followup
1 B1 A 1 1
2 C1 A 1 1
3 D1 A 1 2

有没有办法而不是默认长度它会添加第二个后续列?所以数据会显示如下:
  Patient marker baseline followup.1 followup.2
1 B1 A 1 0 NA
2 C1 A 0 15 NA
3 D1 A 1 2 13

谢谢!

最佳答案

不清楚您在问什么,因为您似乎想在 dcast 中组合两个不同的功能同时。在我看来,您想改进第一个输出而不是第二个输出。如果是这样,一个简单的解决方案就是为 Visit 中的值添加一个自动索引。列然后 dcast .这是使用 data.table 的简单方法包(认为输出不是你想要的,因为我还添加了一个索引 baseline ,但它可以让你开始)

library(data.table)
setDT(mymatrix)[, Visit := paste(Visit, seq_len(.N), sep = "."), list(Patient, Visit)]
dcast.data.table(mymatrix, Patient + marker ~ Visit, value.var = "Number")

# Patient marker baseline.1 followup.1 followup.2
# 1: B1 A 1 0 NA
# 2: C1 A 0 15 NA
# 3: D1 A 1 2 13

关于r - 更改 dcast 以显示多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27515002/

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