我有一个包含30行和2列的数据集。例如:
value <- c(305.19, 30.19, 126.97, 178.89, 640.01, 189.28, 15.92,
219.79, 178.89, 911.61, 178.89, 18.28, 305.19, 322.90,
126.97, 12.97, 178.89, 12.97, 322.90, 158.92, 322.90,
219.79, 911.61, 219.79, 911.61, 325.90, 322.90, 911.61,
158.92, 322.78)
Date <- c("1997-05-01","1997-05-02","1997-05-03","1997-05-04","1997-05-05",
"1997-05-06","1997-05-07","1997-05-08","1997-05-09","1997-05-10",
"1997-05-11","1997-05-12","1997-05-13","1997-05-14","1997-05-15",
"1997-05-16","1997-05-17","1997-05-18","1997-05-19","1997-05-20",
"1997-05-21","1997-05-22","1997-05-23","1997-05-24","1997-05-25",
"1997-05-26","1997-05-27","1997-05-28","1997-05-29","1997-05-30")
data <- data.frame(value, Date)
使用quantile
功能,我可以选择百分比25%,50%,75%之间的值。
例如:
data$value <- data$value[data$value>=quantile(data$value)[4]]
newvalue <- data$value[data$value>=quantile(data$value)[4]]
data$value <- sample(newvalue, dim(data)[1], replace=T)
我想创建一个仅包含随机值的新列 - 较低的12.5%和较高的87.5%。
我该怎么做?
答案 0 :(得分:1)
dplyr解决方案
library(dplyr)
data %>% filter(ntile(value,n=8) %in% 2:7 == TRUE) %>%
do(sample_n(.,30, replace = TRUE))
答案 1 :(得分:0)
我们可以做到
q1 <- quantile(data$value, probs = c(0.125, 0.875))
data$newValue <- sample(data$value[data$value > q1[1] & data$value < q1[2]],
nrow(data), replace = TRUE)