R 计算数据帧中行的总字数

R 计算数据帧中行的总字数,r,R,我有一个每行都有单词的数据框。某些行的示例: df This is a word Another word third word word 我想计算每一行的数量,并将其写入一个新的数据帧,并在最终的csv中包含如下内容: df,total This is a word,4 Another word,2 third word,2 word,1 可能使用空格字符吗?您可以使用str\u count library(stringr) df$total <- str_count(df$df,

我有一个每行都有单词的数据框。某些行的示例:

df
This is a word
Another word
third word
word
我想计算每一行的数量,并将其写入一个新的数据帧,并在最终的csv中包含如下内容:

df,total
This is a word,4
Another word,2
third word,2
word,1

可能使用空格字符吗?

您可以使用
str\u count

library(stringr)
df$total <- str_count(df$df, '\\s+')+1
df$total
#[1] 4 2 2 1


只需使用
strsplit
和您想要的分割,然后计算出来的项目数

df$total <- sapply(df$df, function(x) length(unlist(strsplit(as.character(x), "\\W+"))))

长度(gregexpr(“[[:>:]”,df$df,perl=TRUE))
用于检测由逗号、空格、句号和这些字符的组合分隔的单词。@最近的邮件谢谢,但它在gregexpr([[:>:]”,df$df,perl=TRUE)中给出了错误
错误:无效的正则表达式“[:>:]”“
有任何输入错误吗?@我最近使用的
R3.2.1
邮件对我来说很有效-我回到了3.1.0-
gregexpr(“[[:>:]”,df$df,perl=TRUE)
似乎工作得很好,
length
在这个旧版本上不起作用,但我假设在最新版本上可以正常工作。错误似乎是在
gregexpr
调用中出现的,这很奇怪。@最近的邮件是的,只是
[[:>:]
造成了问题
 lengths(strsplit(df$df, '\\S+'))
 #[1] 4 2 2 1
 count.fields(textConnection(df$df))
 #[1] 4 2 2 1
df$total <- sapply(df$df, function(x) length(unlist(strsplit(as.character(x), "\\W+"))))
              df total
1 This is a word     4
2   Another word     2
3     third word     2
4           word     1