【问题标题】:how can i count the number of times a string appears in my dataframe如何计算字符串出现在我的数据框中的次数
【发布时间】:2020-09-23 15:13:03
【问题描述】:

这是我想要处理的数据框:

df = data.frame(color = c("red", "blue", "red", "blue", "red", "blue", "red", "red"), col_2 = c(1,1,2,2,3,3,4,5))

在此数据框中,每行出现一种颜色的名称,以及与其外观相对应的数字(例如“红色”出现 5 次,因此在数据框中我们有 5 行颜色为“红色”,每个时间它在数据框中出现的次数)

我想创建一个新的数据框,其中: 第一列显示颜色名称,第二列显示该颜色在第一个数据框中出现的次数。

因此,在我的新数据框中,每一行对应一个唯一的颜色,以及它在第一个数据框中出现的次数。 (在这个dataframe中只有2种颜色,但是在真实的dataframe中有很多颜色,这里只是举例)

有人可以帮帮我吗?

【问题讨论】:

  • as.data.frame(table(df[,"color"]))

标签: r string dataframe count dataset


【解决方案1】:
as.data.frame(table(df$color))

返回:

  Var1 Freq
1 blue    3
2  red    5

或者,使用dplyr

library(dplyr)
df %>% 
  group_by(color) %>% 
  count()

返回:

# A tibble: 2 x 2
# Groups:   color [2]
  color     n
  <chr> <int>
1 blue      3
2 red       5

或者使用data.table:

library(data.table)
df <- data.table(df)
df[, .(count = .N),  by = color]

返回:

   color count
1:   red     5
2:  blue     3

【讨论】:

  • as.character(df[order(-df$Freq), ][1,1])
【解决方案2】:

首先获得独特的颜色:

the_colors <- unique(df$color)

然后得到计数:

the_count <- sapply(the_colors, function(x) sum(df$color == x))

现在创建data.frame

new_df = data.frame(colors=the_colors, count=the_count)

这是输出:

> new_df
  colors count
1    red     5
2   blue     3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2021-12-29
    • 2012-10-03
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    相关资源
    最近更新 更多