2016-05-17 70 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) 
相關問題