簡體   English   中英

如何在R中的數據框中組合兩列?

[英]How to combine two columns in a dataframe in R?

我有一個數據框“df”如下:

Samples Status  last_contact_days_to    death_days_to
Sample1 Alive   [Not Available]       [Not Applicable]
Sample2 Dead    [Not Available]             724
Sample3 Dead    [Not Available]            1624
Sample4 Alive      1569               [Not Applicable]
Sample5 Dead    [Not Available]            2532
Sample6 Dead    [Not Available]            1271

我想將列last_contact_days_todeath_days_to組合在一起,在結果中它應該只顯示值而不是任何其他字符。 如果兩列都有字符,則應刪除整行。

結果應如下所示:

Samples Status  new_column
Sample2 Dead    724
Sample3 Dead    1624
Sample4 Alive   1569
Sample5 Dead    2532
Sample6 Dead    1271

我們可以將[Not Available][Not Applicable]更改為NA並使用coalesce

library(tidyverse)
df1 %>%
   mutate_at(3:4, 
      funs(replace(., .%in% c("[Not Available]", "[Not Applicable]"), NA))) %>%
   transmute(Samples, Status,
             new_column = coalesce(last_contact_days_to, death_days_to)) %>%
   filter(!is.na(new_column))
#  Samples Status new_column
#1 Sample2   Dead        724
#2 Sample3   Dead       1624
#3 Sample4  Alive       1569
#4 Sample5   Dead       2532
#5 Sample6   Dead       1271

注意:正如@Roland建議的那樣,如果第3列和第4列除了'[Not Available]','[Not Applicable]'之外只有數值,那么mutate_at可以更改為as.numeric 它將所有非數字元素轉換為NA並帶有友好警告,它不會有任何問題

df1 %>%
    mutate_at(3:4, as.numeric) 
    # if the columns are `factor` class then wrap with `as.character`
    # mutate_at(3:4, funs(as.numeric(as.character(.))))

注意:在OP的數據集中,這些是factor類。 因此,取消注釋上面的代碼並使用它而不是直接應用as.numeric

數據

df1 <- structure(list(Samples = c("Sample1", "Sample2", "Sample3", "Sample4", 
"Sample5", "Sample6"), Status = c("Alive", "Dead", "Dead", "Alive", 
"Dead", "Dead"), last_contact_days_to = c("[Not Available]", 
"[Not Available]", "[Not Available]", "1569", "[Not Available]", 
"[Not Available]"), death_days_to = c("[Not Applicable]", "724", 
"1624", "[Not Applicable]", "2532", "1271")), .Names = c("Samples", 
"Status", "last_contact_days_to", "death_days_to"), 
 class = "data.frame", row.names = c(NA, 
-6L))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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