找到部分相似的字符串元素并汇总数据
find partially similar string elements and summarize the data
我有一个数据集,我想根据(比方说)前三个字符来总结我的数据。事实上,连接列中具有相同 3 个第一个字母的行。例如:
df
title freq
ACM100 3
ACM200 2
ACM300 2
MAT11 1
MAT21 2
CMP00 3
CMP10 3
我想按标题前3个字符汇总数据库并统计频率
result:
title freq
ACM 7
MAT 3
CMP 6
如果能在 R 中帮助我,我将不胜感激。
我们可以用separate
把字母拆分成组,然后用group_by
和summarise
得到想要的结果。
library(tidyverse)
df <- read_table2(
"title freq
ACM100 3
ACM200 2
ACM300 2
MAT11 1
MAT21 2
CMP00 3
CMP10 3"
)
df %>%
separate(title, c("letters", "numbers"), sep = 3) %>%
group_by(letters) %>%
summarise(freq = sum(freq))
#> # A tibble: 3 x 2
#> letters freq
#> <chr> <int>
#> 1 ACM 7
#> 2 CMP 6
#> 3 MAT 3
由 reprex package (v0.2.0) 创建于 2018-10-23。
这有效。
df$firstletters <- substr(df$title,1,3)
df.grouped <- df %>% group_by(firstletters)
df.summarized <- df.grouped %>% summarize(count = sum(freq))
> df.summarized
# A tibble: 3 x 2
firstletters count
<chr> <int>
1 ACM 7
2 CMP 6
3 MAT 3
您可以将 aggregate
与 transform
一起使用
aggregate(freq ~ title, transform(df, title = substr(title, 1, 3)), sum)
# title freq
# 1 ACM 7
# 2 CMP 6
# 3 MAT 3
因为你用 regex 标记了这个问题并且还没有收到 data.table
答案,这里还有一个选项供你选择
library(data.table)
setDT(df)
df[, .(freq = sum(freq)), by = .(title = sub("[0-9]+", "", title))]
# title freq
#1: ACM 7
#2: MAT 3
#3: CMP 6
我有一个数据集,我想根据(比方说)前三个字符来总结我的数据。事实上,连接列中具有相同 3 个第一个字母的行。例如:
df
title freq
ACM100 3
ACM200 2
ACM300 2
MAT11 1
MAT21 2
CMP00 3
CMP10 3
我想按标题前3个字符汇总数据库并统计频率
result:
title freq
ACM 7
MAT 3
CMP 6
如果能在 R 中帮助我,我将不胜感激。
我们可以用separate
把字母拆分成组,然后用group_by
和summarise
得到想要的结果。
library(tidyverse)
df <- read_table2(
"title freq
ACM100 3
ACM200 2
ACM300 2
MAT11 1
MAT21 2
CMP00 3
CMP10 3"
)
df %>%
separate(title, c("letters", "numbers"), sep = 3) %>%
group_by(letters) %>%
summarise(freq = sum(freq))
#> # A tibble: 3 x 2
#> letters freq
#> <chr> <int>
#> 1 ACM 7
#> 2 CMP 6
#> 3 MAT 3
由 reprex package (v0.2.0) 创建于 2018-10-23。
这有效。
df$firstletters <- substr(df$title,1,3)
df.grouped <- df %>% group_by(firstletters)
df.summarized <- df.grouped %>% summarize(count = sum(freq))
> df.summarized
# A tibble: 3 x 2
firstletters count
<chr> <int>
1 ACM 7
2 CMP 6
3 MAT 3
您可以将 aggregate
与 transform
aggregate(freq ~ title, transform(df, title = substr(title, 1, 3)), sum)
# title freq
# 1 ACM 7
# 2 CMP 6
# 3 MAT 3
因为你用 regex 标记了这个问题并且还没有收到 data.table
答案,这里还有一个选项供你选择
library(data.table)
setDT(df)
df[, .(freq = sum(freq)), by = .(title = sub("[0-9]+", "", title))]
# title freq
#1: ACM 7
#2: MAT 3
#3: CMP 6