【问题标题】:Organize subgroup strings (text)组织子组字符串(文本)
【发布时间】:2020-02-15 23:56:45
【问题描述】:

我正在尝试转换类似df 格式的内容:

df <- data.frame(first = c("a", "a", "b", "b", "b", "c"), 
  words =c("about", "among", "blue", "but", "both", "cat"))

df
  first words
1     a about
2     a among
3     b  blue
4     b   but
5     b  both
6     c   cat

改成如下格式:

df1
  first           words
1     a    about, among
2     b blue, but, both
3     c             cat
> 

我试过了

aggregate(words ~ first, data = df, FUN = list)

  first   words
1     a    1, 2
2     b 3, 5, 4
3     c       6

tidyverse:

df %>%
  group_by(first) %>% 
  group_rows()

任何建议将不胜感激!

【问题讨论】:

  • 那些没用的怎么办?
  • 它没有给出我想要的格式words(不是number
  • 如果您在 data.frame 中将参数 stringsAsFactors 设置为 FALSE,您的第一个代码 (aggregate(words ~ first, data = df, FUN = list)) 将起作用。
  • @B.ChristianKamgang 你完全正确!我应该检查一下。我以为是默认的。非常感谢!
  • @B.ChristianKamgang,请添加为未来读者的答案。

标签: r string text aggregate


【解决方案1】:

使用tidyverse,在group_by 之后使用summarisepaste

library(dplyr)
df %>% 
  group_by(first) %>%
  summarise(words = toString(words))
# A tibble: 3 x 2
#  first words          
#  <fct> <chr>          
#1 a     about, among   
#2 b     blue, but, both
#3 c     cat           

或将其保留为list

df %>%
  group_by(first) %>%
  summarise(words = list(words))

【讨论】:

  • 整洁!我真的很喜欢这个。非常感谢。
【解决方案2】:

data.table 解决方案:

library(data.table)

df <- data.frame(first = c("a", "a", "b", "b", "b", "c"), 
  words =c("about", "among", "blue", "but", "both", "cat"))

df <- setDT(df)[, lapply(.SD, toString), by = first]

df
#    first           words
# 1:     a    about, among
# 2:     b blue, but, both
# 3:     c             cat

# convert back to a data.frame if you want
setDF(df)

【讨论】:

    猜你喜欢
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    相关资源
    最近更新 更多