我一直在努力根據另一個資料框中某些行和列的值創建一個新列。我有一個看起來像這樣的資料框:
| 樣品ID | 日期 | 測驗結果 |
|---|---|---|
| 樣品1 | 2022 年 1 月 1 日 | 積極的 |
| 樣品1 | 2022 年 1 月 1 日 | 消極的 |
| 樣品1 | 2022 年 1 月 1 日 | 消極的 |
| 樣品2 | 2022 年 2 月 1 日 | 積極的 |
| 樣品2 | 2022 年 3 月 1 日 | 消極的 |
| 樣品3 | 2022 年 4 月 1 日 | 消極的 |
| 樣品3 | 2022 年 5 月 1 日 | 積極的 |
| 樣品4 | 2022 年 5 月 1 日 | 消極的 |
| 樣品4 | 2022 年 6 月 1 日 | 消極的 |
| 樣品4 | 2022 年 7 月 1 日 | 消極的 |
我想創建一個新列,決定每個樣本 ID 的最終結果。如果樣本在任何日期為陽性,則最終結果將是最早陽性日期的檢測結果,否則樣本為陰性。結果應如下所示:
| 樣品ID | 日期 | 測驗結果 | 最后結果 |
|---|---|---|---|
| 樣品1 | 2022 年 1 月 1 日 | 積極的 | 積極的 |
| 樣品1 | 2022 年 1 月 1 日 | 消極的 | 積極的 |
| 樣品1 | 2022 年 1 月 1 日 | 消極的 | 積極的 |
| 樣品2 | 2022 年 2 月 1 日 | 積極的 | 積極的 |
| 樣品2 | 2022 年 3 月 1 日 | 消極的 | 積極的 |
| 樣品3 | 2022 年 4 月 1 日 | 消極的 | 積極的 |
| 樣品3 | 2022 年 5 月 1 日 | 積極的 | 積極的 |
| 樣品4 | 2022 年 5 月 1 日 | 消極的 | 消極的 |
| 樣品4 | 2022 年 6 月 1 日 | 消極的 | 消極的 |
| 樣品4 | 2022 年 7 月 1 日 | 消極的 | 消極的 |
我確實嘗試過使用 ifelse 和回圈,但沒有成功。我將不勝感激任何幫助。非常感謝。
uj5u.com熱心網友回復:
您可以為此使用庫 dplyr,對 sample_ID 執行 group_by 并檢查任何相應的值是否為正:
library(dplyr)
data = "sample_ID date test_result
sample1 1/1/2022 positive
sample1 1/1/2022 negative
sample1 1/1/2022 negative
sample2 2/1/2022 positive
sample2 3/1/2022 negative
sample3 4/1/2022 negative
sample3 5/1/2022 positive
sample4 5/1/2022 negative
sample4 6/1/2022 negative
sample4 7/1/2022 negative"
df <- read.table(text=data, sep="\t", header = TRUE)
df %>%
group_by(sample_ID) %>%
mutate(final_result = ifelse(any(test_result == 'positive'),'positive','negative')) %>%
ungroup()
uj5u.com熱心網友回復:
您可以group_by sample_ID檢查是否有任何test_resultis "positive":
library(dplyr)
df %>%
group_by(sample_ID) %>%
mutate(final_result = ifelse(any(test_result == "positive"), "positive", "negative"))
輸出
# A tibble: 10 × 4
# Groups: sample_ID [4]
sample_ID date test_result final_result
<chr> <chr> <chr> <chr>
1 sample1 1/1/2022 positive positive
2 sample1 1/1/2022 negative positive
3 sample1 1/1/2022 negative positive
4 sample2 2/1/2022 positive positive
5 sample2 3/1/2022 negative positive
6 sample3 4/1/2022 negative positive
7 sample3 5/1/2022 positive positive
8 sample4 5/1/2022 negative negative
9 sample4 6/1/2022 negative negative
10 sample4 7/1/2022 negative negative
基數 R 的等價物是:
df |>
transform(final_result = ave(test_result, sample_ID,
FUN = \(x) ifelse(any(x == "positive"), "positive", "negative")))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/527700.html
標籤:r数据操作
上一篇:R包'公式'中的警告訊息
