【问题标题】:Data with multiple rows per observations with variables populated in some but not other rows每个观察值具有多行的数据,其中变量填充在某些行中,而不是其他行
【发布时间】:2021-12-16 01:22:56
【问题描述】:

所以我有这个数据框:

dat1 <- data.frame(id=1:n, 
                  group=rep(LETTERS[1:2], n/2),
                  age=sample(18:30, n, replace=TRUE),
                  type=NA,
                  op=factor(paste0("op", 1:n)),
                  x=NA)
dat1
dat2 <- data.frame(id=1:n, 
                   group=rep(LETTERS[1:2], n/2),
                   age=NA,
                   type=factor(paste0("type", 1:n)),
                   op=NA, 
                   x=rnorm(n))
dat <- full_join(dat1,dat2) %>% arrange(id)
dat

   id group age  type   op           x
1   1     A  19  <NA>  op1          NA
2   1     A  NA type1 <NA>  0.18819303
3   2     B  29  <NA>  op2          NA
4   2     B  NA type2 <NA>  0.11916096
5   3     A  19  <NA>  op3          NA
6   3     A  NA type3 <NA> -0.02509255
7   4     B  28  <NA>  op4          NA
8   4     B  NA type4 <NA>  0.10807273
9   5     A  27  <NA>  op5          NA
10  5     A  NA type5 <NA> -0.48543524
11  6     B  26  <NA>  op6          NA
12  6     B  NA type6 <NA> -0.50421713

此数据集的每个观测值有多行,而一些变量存储在一行中,而另一些则存储在另一行中。我喜欢整齐的格式,每个 id 只有一行。我可以过滤成两个数据框然后重新加入,但必须有更简单的方法。总结会起作用,但只能使用数字变量.. 分组是固定id,不同分组没有相同的id

  group_by(id) %>% 
  summarise_if(is.numeric, sum, na.rm=T)
data

似乎必须有一个非常简单的解决方案,但我想不通。感谢您的帮助!

【问题讨论】:

  • 不确定是否应将其标记为与此重复:stackoverflow.com/questions/28036294/…。由于该问题仅用于数字示例,并且某些答案仅针对该情况。但是这个问题需要一个一般情况。

标签: r dplyr summarize


【解决方案1】:

tmfmnkthis回答到类似的问题,您应该可以通过在末尾添加此代码块来解决此问题:

dat <- dat %>%
  group_by(id) %>%
  summarize(across(everything(), ~ first(na.omit(.))))
dat

链接中的问题只是数字的特例,但这个代码块应该可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2023-02-04
    • 2021-07-19
    相关资源
    最近更新 更多