簡體   English   中英

將數據框拆分為兩組

[英]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分成兩組: highlow 當我繪制分割count_sim_df ,它應該看起來像這樣(綠色和藍色的所有內容都是photoshopped)。 我正在尋找棘手位越來越之間的重疊highlow圍繞的中間值tide

這就是我想將count_sim_df分為高和低的方式:

  • count_sim_df一半分配給high和一半count_sim_dflow
  • 重新分配的值count之間創建重疊highlow圍繞的中間值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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM