2016-05-17 64 views
0

我想计算机的这些下列字符的数目:计算数据框每一行中给定字符出现的次数?

"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 

我看过很多剧本,但他们都没有做我想要做的事情。

+2

请添加代码为我们重新创建数据frame.Also添加什么是预期的输出 – sachinv

+0

http://stackoverflow.com/a/19667053/244811 – sweaver2112

+1

试试'cbind(df1,t(apply(df1 [-1],1,function(x)sapply(v1,function(y )length(grep(y,x)))))'其中'v1'是值的向量 – akrun

回答

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

您可以添加到您的data.frame使用cbind

allDone <- cbind(temp, myCounts)