gpt4 book ai didi

r - 具有其中一列的倒数第二个值的数据框的子集

转载 作者:行者123 更新时间:2023-12-02 05:04:48 25 4
gpt4 key购买 nike

我有一个包含很多列的 data.frame,其中一列包含样本区域的代码,另一列包含样本的编号。我想从每个样本区域的倒数第二个样本中提取信息。我尝试了很多不同的东西……最后这是我最好的猜测……但它仍然没有用。

site <- sample (1:3, 10, replace= T)
d2 <- sample (1:5, 10, replace= T)
d3 <- sample (1:5, 10, replace= T)
samplet <- sample (1:4, 10, replace= T)
mydata <- data.frame (cbind(site, d2, d3, samplet))

penultimate <- matrix(NA,,) # here I dont know how the return will be, as I dont know how the dataframe will change
si <- matrix (NA, , )
pl <- unique (site)
for (i in 1:(length (pl))) {
si <- mydata[which (samplet==pl[i]),] # I tried to create a temporary matrix, so I can calculate each site at a time
penultimate <- si[which (si$samplet!=(max(si$samplet[si$samplet!=max(si$samplet)]))),]
}

干杯!

最佳答案

一种简单的方法是使用data.table 及其内置的.N

# assuming `d1` is the column from which you want to find the penultimate

mydata <- data.frame(d1=strsplit("AAABBCCCCCDD", "")[[1]], d2=rnorm(12), d3=LETTERS[1:12], d4=c(101:103, 201:202, 301:305, 401:402))

DT <- data.table(mydata)

DT[, .SD[.N-1], by=d1]

d1 d2 d3 d4
1: A 1.6906714 B 102
2: B -0.1239458 D 201
3: C -0.2976339 I 304
4: D 0.6858120 K 401

与我的数据比较

> mydata
d1 d2 d3 d4
1 A 0.5986002 A 101
2 A 1.6906714 B 102 <~~~~ \
3 A -0.3253657 C 103
4 B -0.1239458 D 201 <~~~~ -\
5 B 0.8261401 E 202
6 C 0.0601318 F 301 Penultimate Values by d1
7 C -0.9766622 G 302
8 C 0.1028259 H 303
9 C -0.2976339 I 304 <~~~~~ -/
10 C -1.1467000 J 305
11 D 0.6858120 K 401 <~~~~~ /
12 D -0.6160335 L 402

编辑,更新了新的样本数据。

关于r - 具有其中一列的倒数第二个值的数据框的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16423432/

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