gpt4 book ai didi

r - 一个单元格中的多个值

转载 作者:行者123 更新时间:2023-12-03 20:35:24 26 4
gpt4 key购买 nike

我的数据看起来有点像这样:

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

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

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

最佳答案

如果我们需要总数,那么另一种选择是子集化后的str_count

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

或者使用 base R 中的 gregexpr

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))

关于r - 一个单元格中的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47608704/

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