gpt4 book ai didi

随机删除条件为 R 的行(又名 rdeleteIf)

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

我有数据框x:

Button TrackNo  NextTime
54 G155 2011-04-29 19:20:04
50 H54 2011-04-29 19:25:41
54 G157 2011-04-29 19:47:58

我需要删除 30%(均匀地)具有 button==54 的行(IE。)。我该怎么做?

我知道如何删除条件,比如 a <- x[x[,1]==54,]我知道如何随机删除,比如 i <- runif(1,length(x)); a <- x[,i]

但是如何同时进行呢?

最佳答案

@shadow 已经在评论中用一个衬里回答了,但这里有一个工作流程,说明您将来可以如何处理这些事情。一旦你理解了这一点,你很快就会写出像@shadow 这样的代码。

# generate some fake data (the kind you should provide when asking questions)
mydf <- data.frame(button = sample(1:5, 100, replace = TRUE), var1 = runif(100))

find.button.5 <- mydf$button == 5 # find row numbers where button == 5
perc.30 <- round(sum(find.button.5) * 0.3) # find 30% of button 5
button.5 <- which(find.button.5 == TRUE)
sampled.30 <- sample(button.5, perc.30) # row numbers of 30% of button 5
mydf[-sampled.30, ] # in your final output, include all but the 30%

> nrow(mydf[-sampled.30, ])
[1] 93

请注意,您的最终输出中缺少 sampled.30 中的行。

关于随机删除条件为 R 的行(又名 rdeleteIf),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20322742/

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