如果不同的值,将列值合并为一个。

3
我有一个看起来像这样的df:
ID   LOC
1     A
1     A
2     A
2     B
3     A
3     A
3     A
4     A
4     B
4     C

我想要做的是将每个ID的LOC值合并为一行,如果它们相同,则保持为一个值,因此我的输出将是:
ID   LOC
1     A
2     A + B
3     A
4     A + B + C

现在我正在使用:

group_by(ID) %>%
mutate(concat_LOC = paste0(LOC, collapse = " + ")) 

将所有值连接起来,即使它们相同。
2个回答

5
  1. 你正在进行减少/汇总操作,因此应使用summarize而不是mutate
  2. 如果你确实想要重复LOC的值,请使用unique
dat %>%
  group_by(ID) %>%
  summarize(LOC = paste(unique(LOC), collapse = " + ")) %>%
  ungroup()
# # A tibble: 4 x 2
#      ID LOC      
#   <int> <chr>    
# 1     1 A        
# 2     2 A + B    
# 3     3 A        
# 4     4 A + B + C

请参考一下,与此相关的内容:https://dev59.com/vWgu5IYBdhLWcg3wHjl7 - r2evans

0

在R语言中,有很多种方法可以实现同一个目的,下面是使用Base、tidyverse和data.table三种方式:

# Base R solution: res => data.frame
res <- aggregate(
  LOC ~ ID,
  df, 
  FUN = function(x){
    paste0(unique(x), collapse = ' + ')
  }
)

# Output data.frame to console: data.frame => stdout(console) 
res

# Tidyverse method: tv_res => tibble
library(tidyverse)
tv_res <- df %>% 
  group_by(ID) %>% 
  distinct() %>% 
  summarise(LOC = str_c(LOC, collapse = ' + ')) %>% 
  ungroup()


# Print the data.frame to the console: 
# tibble => stdout(console)
tv_res

# Data.table method: 
# Coerce data.frame to data.table: dt => data.table object
dt <- data.table(df)

# Aggregate the data.table: dt_res => data.table object
dt_res <- dt[, 
          list(LOC = paste(unique(LOC), collapse = ' + ')),
          by = ID]

# Print the data to the console: data.table => console(stdout)
dt_res

使用的数据:

# Import the data: df => data.frame 
df <- structure(list(ID = c(1L, 1L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L), 
LOC = c("A", "A", "A", "B", "A", "A", "A", "A", "B", "C")), 
class = "data.frame", row.names = c(NA, -10L))

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