gpt4 book ai didi

在 R 中读取字符串并组合相似的术语

转载 作者:行者123 更新时间:2023-12-04 07:24:05 25 4
gpt4 key购买 nike

我有一个贯穿整个词根的数据框,并想将它们合并到 r 中,我该怎么做?
我想拿这样的东西......

  Name        Count Location
<chr> <dbl> <chr>
1 Car_street 1 A
2 Car_garaged 3 A
3 Car 2 A
4 Bird_fly 3 A
5 Bird_landed 2 A
6 Bird 2 A
7 Plane_fly 3 A
8 Plane_landed 2 A
9 Plane 1 A
并制作这个
  Name        Count Location
<chr> <dbl> <chr>
1 Car 6 A
2 Bird 7 A
7 Plane 6 A
我仍在学习 r,因此向我指出任何方向都可以,我感谢您的帮助。

最佳答案

我们可以删除 _ 后面的子串(包括 _ )并按操作做一个分组

library(dplyr)
df1 %>%
group_by(Name = trimws(Name, whitespace = "_.*"), Location) %>%
summarise(Count = sum(Count), .groups = 'drop')
-输出
# A tibble: 3 x 3
Name Location Count
<chr> <chr> <int>
1 Bird A 7
2 Car A 6
3 Plane A 6

或使用 aggregatebase R
aggregate(Count ~ ., transform(df1, Name = trimws(Name, whitespace = "_.*")), sum)
Name Location Count
1 Bird A 7
2 Car A 6
3 Plane A 6
数据
df1 <- structure(list(Name = c("Car_street", "Car_garaged", "Car", "Bird_fly", 
"Bird_landed", "Bird", "Plane_fly", "Plane_landed", "Plane"),
Count = c(1L, 3L, 2L, 3L, 2L, 2L, 3L, 2L, 1L), Location = c("A",
"A", "A", "A", "A", "A", "A", "A", "A")),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9"))

关于在 R 中读取字符串并组合相似的术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68309975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com