![](/img/trans.png)
[英]Groupby, mutate a new column based on conditions of one column is in the specific ranges of another numeric column
[英]In R how to mutate a numeric column into one new column using various conditions?
我正在嘗試根據原始列的值在 dataframe 中創建一個新列,其中根據值的不同條件將其分為四組。 我不知道該怎么做!
假設一個帶有分數(數值 0-1000)的列作為更大的 dataframe 的一部分。
我想根據以下條件對該分數進行分組的新列:
根據上述條件,我希望新列類似於“Score_status”和 label 它們“無”、“低”、“中”、“高”。 需要忽略所有 0 來計算百分位數,因為當分成分位數時 Q1 和 Q2 都是 0,因此試圖使這個新列看到分數 0 之外的數據分布(這是針對 Kaplan-Meier)。
我希望有人能幫幫忙。 我無法完全理解我將如何做到這一點。
謝謝。
您可以編寫一個 function,即 map 的值到 label。這允許您計算 function 中數據子集的切點。
一個(低效的)實現的例子:
cut_with_none <- function(x, none_value, none_label, quant, break_labels) {
y <- x == none_value
q_val <- quantile(x[!y], quant)
res <- vector(mode = "character", length = length(x))
for(i in rev(seq_along(q_val))) {
res[x <= q_val[i]] <- break_labels[i]
}
res[y] <- none_label
res
}
在哪里:
您可以使用 mutate 輕松添加包含 function 的列。
例如隨機數據:
tibble(subject = sample(letters[1:3], 10, replace = TRUE),
value = rgeom(10, 0.5)) %>%
mutate(label_value = cut_with_none(value, 0, "none",
quant = c(1/3, 2/3, 1),
break_labels = c("low", "middle", "high")))
希望即使它根本不優雅也能做到這一點。
這是使用cut
的一種方法。 創建一個索引idx
,其中包含要從百分位評估中忽略的 0 值的行號。 下面是一個隨機數據的簡單示例(一個值為零)。
set.seed(42)
df <- data.frame(
var = sample(0:9, 10)
)
idx <- df$var != 0
df$score_status <- factor(NA_character_, levels = c("none", "low", "middle", "high"))
df$score_status[idx] <- cut(
df$var[idx],
breaks = quantile(df$var[idx], probs = c(0, 1/3, 2/3, 1)),
include.lowest = TRUE,
labels = c("low", "middle", "high")
)
df$score_status[!idx] <- "none"
df
Output
var score_status
1 0 none
2 4 middle
3 9 high
4 7 high
5 1 low
6 3 low
7 5 middle
8 8 high
9 6 middle
10 2 low
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.