簡體   English   中英

R合並數據/擴展數據集

[英]R merge data /expand data set

我正在嘗試使用R擴展數據集。我記錄了每個樣本的觀察值,並根據這些觀察值計算了百分比。 現在,我需要擴展每個樣本以列出每個可能的觀察結果而無需進行任何計算。 myData的示例:起始數據集:

Sample    Observation    Percent
A         Y              50
A         N              50
B         Y              10
B         N              80
B         Don't know     10 

所需的數據集:

Sample    Observation    Percent
A         Y              50
A         N              50
A         Don't know     NA
B         Y              10
B         N              80
B         Don't know     10 

因此,在這種情況下,我將需要擴展所有樣本A以包括“未知”類別,並用“ NA”填充。

我努力了

myTable <- table(myData)
TableFrame2 <- data.frame(myTable)

這會擴展數據集,但會弄亂“百分比”列(為什么)。 我以為可以將百分比合並回去,但是我需要將該列與示例列和觀察列的擴展集進行匹配,以實現完全匹配。 有什么建議么?

一種方法是將組合合並/合並回到數據中。 (我對數據進行了一些更改,以使其易於在SO中復制/粘貼。)

dat <- read.table(header=TRUE, stringsAsFactors=FALSE, text='
Sample    Observation    Percent
A         Y              50
A         N              50
B         Y              10
B         N              80
B         Don_t_know     10 ')

基數R

merge(
  dat,
  expand.grid(Sample = unique(dat$Sample),
              Observation = unique(dat$Observation),
              stringsAsFactors = FALSE),
  by = c("Sample", "Observation"),
  all = TRUE
)
#   Sample Observation Percent
# 1      A  Don_t_know      NA
# 2      A           N      50
# 3      A           Y      50
# 4      B  Don_t_know      10
# 5      B           N      80
# 6      B           Y      10

Tidyverse:

library(dplyr)
library(tidyr)

dat %>%
  full_join(
    crossing(Sample = unique(dat$Sample), Observation = unique(dat$Observation)),
    by = c("Sample", "Observation")
  )
#   Sample Observation Percent
# 1      A           Y      50
# 2      A           N      50
# 3      B           Y      10
# 4      B           N      80
# 5      B  Don_t_know      10
# 6      A  Don_t_know      NA

甚至

dat %>%
  full_join(expand(., Sample, Observation))
# Joining, by = c("Sample", "Observation")
#   Sample Observation Percent
# 1      A           Y      50
# 2      A           N      50
# 3      B           Y      10
# 4      B           N      80
# 5      B  Don_t_know      10
# 6      A  Don_t_know      NA

暫無
暫無

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

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