gpt4 book ai didi

r - 如何计算每个列中 ","的数量

转载 作者:行者123 更新时间:2023-12-04 00:13:17 25 4
gpt4 key购买 nike

我有一个奇怪的问题。如果我有一个句子,我想计算每个句子中有多少个“,”,并且新变量number等于number of , + 1。我怎样才能做到这一点?看起来像这样的东西:

enter image description here

可以使用代码构建示例数据:

df<-structure(list(Outcome = c("Happy, New", "Year, to, you", "this", 
"is, a , very", "strange, question")), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))

最佳答案

str_count 更容易统计字数

library(stringr)
library(dplyr)
df %>%
mutate(Number = str_count(Outcome, "\\w+"))

-输出

# A tibble: 5 x 2
# Outcome Number
# <chr> <int>
#1 Happy, New 2
#2 Year, to, you 3
#3 this 1
#4 is, a , very 3
#5 strange, question 2

如果有两个或多个单词且分隔符为,,则统计,并加1

df %>%
mutate(Number = str_count(Outcome, ",") + 1)

或在 base R 中带有 strsplitlengths

df$Number <- lengths(strsplit(df$Outcome, ",\\s*"))

关于r - 如何计算每个列中 ","的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66554558/

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