[英]Split dataframe into two groups
我已經模擬了這個data.frame
:
library(plyr); library(ggplot2)
count <- rev(seq(0, 500, 20))
tide <- seq(0, 5, length.out = length(count))
df <- data.frame(count, tide)
count_sim <- unlist(llply(count, function(x) rnorm(20, x, 50)))
count_sim_df <- data.frame(tide=rep(tide,each=20), count_sim)
它可以像這樣繪制:
ggplot(df, aes(tide, count)) + geom_jitter(data = count_sim_df, aes(tide, count_sim), position = position_jitter(width = 0.09)) + geom_line(color = "red")
我現在想把count_sim_df
分成兩組: high
和low
。 當我繪制分割count_sim_df
,它應該看起來像這樣(綠色和藍色的所有內容都是photoshopped)。 我正在尋找棘手位越來越之間的重疊high
和low
圍繞的中間值tide
。
這就是我想將count_sim_df
分為高和低的方式:
count_sim_df
一半分配給high
和一半count_sim_df
為low
count
之間創建重疊high
和low
圍繞的中間值tide
這是我修改過的建議。 我希望它有所幫助。
middle_tide <- mean(count_sim_df$tide)
hilo_margin <- 0.3
middle_df <- subset(count_sim_df,tide > (middle_tide * (1 - hilo_margin)))
middle_df <- subset(middle_df, tide < (middle_tide * (1 + hilo_margin)))
upper_df <- count_sim_df[count_sim_df$tide > (middle_tide * (1 + hilo_margin)),]
lower_df <- count_sim_df[count_sim_df$tide < (middle_tide * (1 - hilo_margin)),]
idx <- sample(2,nrow(middle_df), replace = T)
count_sim_high <- rbind(middle_df[idx==1,], upper_df)
count_sim_low <- rbind(middle_df[idx==2,], lower_df)
p <- ggplot(df, aes(tide, count)) +
geom_jitter(data = count_sim_high, aes(tide, count_sim), position = position_jitter(width = 0.09), alpha=0.4, col=3, size=3) +
geom_jitter(data = count_sim_low, aes(tide, count_sim), position = position_jitter(width = 0.09), alpha=0.4, col=4, size=3) +
geom_line(color = "red")
我可能仍然沒有完全理解你的程序分為高和低,尤其是“重新分配計數值”的意思。 在這種情況下,我在tide
的中間值周圍定義了30%的重疊區域,並將該過渡區域內隨機的一半點分配給“高”,另一半分配給“低”集。
這是一種使用相對較少的代碼生成樣本數據集和分組的方法,只需使用基數R:
library(ggplot2)
count <- rev(seq(0, 500, 20))
tide <- seq(0, 5, length.out = length(count))
df <- data.frame(count, tide)
count_sim_df <- data.frame(tide = rep(tide,each=20),
count = rnorm(20 * nrow(df), rep(count, each = 20), 50))
margin <- 0.3
count_sim_df$`tide level` <-
with(count_sim_df,
factor((tide >= quantile(tide, 0.5 + margin / 2) |
(tide >= quantile(tide, 0.5 - margin / 2) & sample(0:1, length(tide), TRUE))),
labels = c("Low", "High")))
ggplot(df, aes(x = tide, y = count)) +
geom_line(colour = "red") +
geom_point(aes(colour = `tide level`), count_sim_df, position = "jitter") +
scale_colour_manual(values = c(High = "green", Low = "blue"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.