我想计算以下这些字符的数量:
"AAA", "BBB", "CCC","DDD","EEE","FFF"
在像这样的数据框架中
Id Var1 Var2 Var3 Var4
1 xtAAA bBBB fCCC ::hFF
2 xtAAA ZEEE ::FFF
3 ooCCC bBBB CkCC
4 BBBh fCCC :-LLL
5 xtAAA lBBB eCCC ::FFF
6 BBBC
7 xtAAA CvCC fCCC BBBlF
然后获得一个新的数据框:
Id Var1 Var2 Var3 Var4 number.of.AAA number.of.BBB number.of.CCC
1 xtAAA bBBB fCCC ::hFF
2 xtAAA ZEEE ::FFF
3 ooCCC bBBB CkCC
4 BBBh fCCC :-LLL
5 xtAAA lBBB eCCC ::FFF
6 BBBC
7 xtAAA CvCC fCCC BBBlF
我见过许多剧本,但没有一部分是我的目标。
答案 0 :(得分:1)
以下应该做你想做的事:
# smaller subset of the data
temp <- data.frame(matrix(c("xtAAA", "bBBB", "fCCC", "::hFF", "xtAAA","ZEEE", "::FFF"), byrow = T), stringsAsFactors=F)
# build a little counter function
counter <- function(strings, input) {
return(sapply(strings, function(i) sum(grepl(i, input))))
}
# get the counts
myCounts <- t(sapply(1:nrow(temp), function(i) counter(strings=c("AAA", "BBB", "CCC"), temp[i,])))
您可以使用cbind
allDone <- cbind(temp, myCounts)