一个单元格中的多个值

时间:2017-12-02 14:03:55

标签: r dataframe count

我的数据看起来与此类似:

number    type    results
1         5       x, y, z
2         6       a
3         8       x
1         5       x, y

基本上,我在Excel中有数据在几个单独的单元格中有逗号,我需要计算每个由逗号分隔的值,在通过子集化满足某个要求之后。

问题:在R中用数字== 1和类型== 5对数据进行子集化时如何接收5的总和?

3 个答案:

答案 0 :(得分:2)

如果我们需要总计数,那么在子集化后的另一个选项是str_count

library(stringr)
with(df, sum(str_count(results[number==1 & type==5], "[a-z]"), na.rm = TRUE))
#[1] 5

gregexpr

中的base R
with(df, sum(lengths(gregexpr("[a-z]", results[number==1 & type==5])), na.rm = TRUE))
#[1] 5

如果元素没有匹配模式,请使用

with(df, sum(unlist(lapply(gregexpr("[a-z]", 
         results[number==1 & type==5]), `>`, 0)), na.rm = TRUE))

答案 1 :(得分:1)

以下是使用dplyrtidyr的选项。 filter函数可以根据条件过滤行。 separate_rows可以分隔逗号。 group_by是对数据进行分组。 tally可以计算数字。

dt2 <- dt %>%
  filter(number == 1, type == 5) %>%
  separate_rows(results) %>%
  group_by(results) %>%
  tally()
# # A tibble: 3 x 2
#   results     n
#     <chr> <int>
# 1       x     2
# 2       y     2
# 3       z     1

或者您只能使用count(results),如下面的代码所示。

dt2 <- dt %>%
  filter(number == 1, type == 5) %>%
  separate_rows(results) %>%
  count(results)

数据

dt <- read.table(text = "number    type    results
1         5       'x, y, z'
                 2         6       a
                 3         8       x
                 1         5       'x, y'",
                 header = TRUE, stringsAsFactors = FALSE)

答案 2 :(得分:1)

以下是使用基础R的方法。您在逗号上分割results并获取每个列表的长度,然后按number添加这些分组。

aggregate(sapply(strsplit(df$results, ","), length), list(df$number), sum)
  Group.1 x
1       1 5
2       2 1
3       3 1

您的数据:

df = read.table(text="number    type    results
1         5       'x, y, z'
2         6       'a'
3         8       'x'
1         5       'x, y'",
header=TRUE, stringsAsFactors=FALSE)