按组折叠具有非缺失字符值的行

5

我试图通过组将行合并/聚合/汇总,只保留非缺失值,其中值为字符。以下是可重现的示例。

df = data.frame(store = c("A","A", "B","B"),
                item1=c("apple","","milk",""),
                item2=c("","pear","","bread"))

df
  store item1 item2
1     A apple      
2     A        pear
3     B  milk      
4     B       bread

我希望将df更改为以下内容:
df2
  store item1 item2
1     A apple  pear
2     B  milk bread

我曾尝试使用summarise_all的以下语句,但似乎没有起作用:nchar(.) > 0

df %>%
  group_by(store) %>%
  summarise_all( ~ + any(nchar(.) > 0))

欢迎提供任何意见!

2个回答

2

您可以做:

df %>%
 group_by(store) %>%
 summarise_all(~ .[nchar(.) > 1])

  store item1 item2
  <chr> <chr> <chr>
1 A     apple pear 
2 B     milk  bread

1

1) pivot 将数据重塑为长格式,去除 "" 元素并重新重塑回去。

library(dplyr)
library(tidyr)

df %>%
  pivot_longer(-1) %>%
  filter(value != "") %>%
  pivot_wider

提供:

# A tibble: 2 x 3
  store item1 item2
  <fct> <fct> <fct>
1 A     apple pear 
2 B     milk  bread

2) max 另一种方法是在组内取最大值,不包括NA。这会将项目列转换为字符类型,而(1)的输出结果是因子列。

library(dplyr)

df %>%
  group_by(store) %>%
  summarize_all(~ max(as.character(.), na.rm = TRUE)) %>%
  ungroup

提供:

# A tibble: 2 x 3
  store item1 item2
  <fct> <chr> <chr>
1 A     apple pear 
2 B     milk  bread

不知道max函数也适用于字符。谢谢! - qnp1521
请注意,在使用max()函数时,需要仔细考虑您的group_by()。当按多个列进行分组时,可能会产生意想不到的结果。 - Pake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接