![](/img/trans.png)
[英]R: Aggregating data by column group - mutate column with values for each observation
[英]mutate a column by group and replacing to its 4 median values in R
我有一個數據集:
set.seed(1)
data.frame(grouping1 = rep(c("A", "B", "C"), each = 12),
grouping2 = rep(rep(c("exp1", "exp2", "exp3"), each = 3), times = 4),
value = runif(36))
我想將 A 組中的值替換為以每個分組 1 的中位數為中心的 4 個值(在這種情況下是第 5、第 6、第 7 和第 8 個值)。 然后為每個實驗重復這些值(分組 2)。 每個 exp 中的順序無關緊要,因為我將取每個實驗的平均值。
嘗試使用 tidyverse 執行此操作時,我有兩個困難:
也許需要自定義功能。
這是預期的輸出:
set.seed(1)
new_value = runif(36)
new_value[1:12] <- rep(sort(runif(36)[1:12])[5:8],3)
data.frame(grouping1 = rep(c("A", "B", "C"), each = 12),
grouping2 = rep(rep(c("exp1", "exp2", "exp3"), each = 4), times = 3),
value = new_value)
這是使用 base 的一種方法。 我改變了輸入df
有相同數量的grouping2
每個grouping1
到您想要的輸出相匹配。 讓我知道這是否是一個問題。 我將包含更新值的字段命名為value2
以使質量控制更容易一些。
set.seed(1)
df<- data.frame(grouping1 = rep(c("A", "B", "C"), each = 12),
grouping2 = rep(rep(c("exp1", "exp2", "exp3"), each = 4), times = 3),
value = runif(36))
# We are only interested in Group A
a <- df[df$grouping1 == "A",]
# Calculate difference between median and values
a$diff <- abs(median(a$value) - a$value)
# Values with smallest absolute difference are centered around the median
a <- a[order(a$grouping2),]
a$value2 <- a[a$diff %in% head(sort(a$diff), 4), "value"]
# Join `a` with original dataframe
df$value2 <- NA
rbind(a[,names(df)], df[df$grouping1 != "A",])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.