gpt4 book ai didi

r - 将行旋转为具有每个测量值 R 的计数值的列

转载 作者:行者123 更新时间:2023-12-04 23:42:45 26 4
gpt4 key购买 nike

我有一个正在使用的示例数据框

ID <- c("A","A","A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B")
TARG_AVG <- c(2.1,2.1,2.1,2.1,2.1,2.1,2.3,2.3,2.5,2.5,2.5,2.5,3.1,3.1,3.1,3.1,3.3,3.3,3.3,3.3,3.5,3.5)
Measurement <- c("Len","Len","Len","Wid","Ht","Ht","Dep","Brt","Ht","Ht","Dep","Dep"
,"Dep","Dep","Len","Len","Ht","Ht","Brt","Brt","Wid","Wid")
df1 <- data.frame(ID,TARG_AVG,Measurement)

我试图在这里解决 3 个不同的问题

1) 我想获得 (ID & TARG_AVG) 分组有多少唯一度量的摘要。我目前这样做
unique <- summaryBy(Measurement~ID+TARG_AVG, data=df1, FUN=function(x) { c(Count=length(x)) } ) 

这给了我总数(measurement.count),但我也想要每个测量的计数。 我想要的输出
  ID TARG_AVG Len Wid Ht Dep Brt Measurement.Count
1 A 2.1 3 1 2 0 0 6
2 A 2.3 0 0 0 1 1 2
3 A 2.5 0 0 2 2 0 4
4 B 3.1 2 0 0 2 0 4
5 B 3.3 0 0 2 0 2 4
6 B 3.5 0 2 0 0 0 2

2) 获得上述输出后,我想对行进行子集化,以便获得过滤后的输出,该输出返回至少有 2 个测量值的行 > 2 .这里 我想要的输出 将是
  ID TARG_AVG Len Wid Ht Dep Brt Measurement.Count
1 A 2.1 3 1 2 0 0 6
3 A 2.5 0 0 2 2 0 4
4 B 3.1 2 0 0 2 0 4
5 B 3.3 0 0 2 0 2 4

3) 最后,我想将列转回只有测量值的行 > 2 . 我想要的输出 这里将是
      ID TARG_AVG Measurement
1 A 2.1 Len
2 A 2.1 Len
3 A 2.1 Len
4 A 2.1 Ht
5 A 2.1 Ht
6 A 2.5 Ht
7 A 2.5 Ht
8 A 2.5 Dep
9 A 2.5 Dep
10 B 3.1 Len
11 B 3.1 Len
12 B 3.1 Dep
13 B 3.1 Dep
14 B 3.3 Ht
15 B 3.3 Ht
16 B 3.3 Brt
17 B 3.3 Brt

我目前正在学习 reshape2、dplyr 和 data.table 包,如果有人能通过向我指出正确的方向来帮助我解决这个问题,那将非常有用。

最佳答案

最新解决方案

library(data.table) #v 1.9.6+
setDT(df1)[, indx := .N, by = names(df1)
][indx > 1, if(uniqueN(Measurement) > 1) .SD, by = .(ID, TARG_AVG)]
# ID TARG_AVG Measurement indx
# 1: A 2.1 Len 3
# 2: A 2.1 Len 3
# 3: A 2.1 Len 3
# 4: A 2.1 Ht 2
# 5: A 2.1 Ht 2
# 6: A 2.5 Ht 2
# 7: A 2.5 Ht 2
# 8: A 2.5 Dep 2
# 9: A 2.5 Dep 2
# 10: B 3.1 Dep 2
# 11: B 3.1 Dep 2
# 12: B 3.1 Len 2
# 13: B 3.1 Len 2
# 14: B 3.3 Ht 2
# 15: B 3.3 Ht 2
# 16: B 3.3 Brt 2
# 17: B 3.3 Brt 2

或者 dplyr相等的
df1 %>%
group_by(ID, TARG_AVG, Measurement) %>%
filter(n() > 1) %>%
group_by(ID, TARG_AVG) %>%
filter(n_distinct(Measurement) > 1)

较旧的解决方案
library(data.table)
## dcast the data (no need in total)
res <- dcast(df1, ID + TARG_AVG ~ Measurement)
## filter by at least 2 incidents of at least length 2
res <- res[rowSums(res[-(1:2)] > 1) > 1,]
## melt the data back and filter again by at least 2 incidents
res <- melt(setDT(res), id = 1:2)[value > 1]
## Expand the data back
res[, .SD[rep(.I, value)]]

原题的解答

这是使用 reshape2 的可能解决方案

第一步
library(reshape2)
res <- dcast(df1, ID + TARG_AVG ~ Measurement, margins = "Measurement")

第二步
res <- res[res$"(all)" > 2,]

3d 步骤
library(data.table)
setDT(df1)[, if(.N > 2) .SD, by = .(ID, TARG_AVG)]

关于r - 将行旋转为具有每个测量值 R 的计数值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33003929/

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