计算数据框中一个 char 变量的所有字母 (26)
Count all the letters (26) of one of the char variable in a dataframe
我有一个包含几列的数据框,如下所示:
Attr Description
60 asdfg asdg dfs
50 smlefekl dewld ewf
35 kojewdfhef e
我只需要创建额外的 26 列,其中包含一行中每个字母的计数。我知道我可以使用:
table(unlist(strsplit(mydata, ""), use.names=FALSE))
对于矢量,但如何为数据框更新它?
如果我们使用 strsplit
,那么我们可能需要创建一个 factor
,其中 levels
指定为 'letters'
d1 <- stack(setNames(strsplit(df1$Description, ""), seq_len(nrow(df1))))
d2 <- subset(d1, values != " ")
d2$values <- factor(d2$values, levels = letters)
t(table(d2))
# values
# ind a b c d e f g h i j k l m n o p q r s t u v w x y z
# 1 2 0 0 3 0 2 2 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0
# 2 0 0 0 2 4 2 0 0 0 0 1 3 1 0 0 0 0 0 1 0 0 0 2 0 0 0
# 3 0 0 0 1 3 2 0 1 0 1 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0
或者如评论中所示,通过循环 'letters' 使用 stringr
中的 str_count
获取 'Description' 的每一行的该字母的计数
library(stringr)
t(sapply(letters, function(x) str_count(df1$Description, x)))
我有一个包含几列的数据框,如下所示:
Attr Description
60 asdfg asdg dfs
50 smlefekl dewld ewf
35 kojewdfhef e
我只需要创建额外的 26 列,其中包含一行中每个字母的计数。我知道我可以使用:
table(unlist(strsplit(mydata, ""), use.names=FALSE))
对于矢量,但如何为数据框更新它?
如果我们使用 strsplit
,那么我们可能需要创建一个 factor
,其中 levels
指定为 'letters'
d1 <- stack(setNames(strsplit(df1$Description, ""), seq_len(nrow(df1))))
d2 <- subset(d1, values != " ")
d2$values <- factor(d2$values, levels = letters)
t(table(d2))
# values
# ind a b c d e f g h i j k l m n o p q r s t u v w x y z
# 1 2 0 0 3 0 2 2 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0
# 2 0 0 0 2 4 2 0 0 0 0 1 3 1 0 0 0 0 0 1 0 0 0 2 0 0 0
# 3 0 0 0 1 3 2 0 1 0 1 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0
或者如评论中所示,通过循环 'letters' 使用 stringr
中的 str_count
获取 'Description' 的每一行的该字母的计数
library(stringr)
t(sapply(letters, function(x) str_count(df1$Description, x)))