我有這樣伯爵出現並排除失蹤
aa<-structure(c("AABB", "AABB", NA, "AABB", "AABB", "AABB", "AABB",
"AABB", "AABB", "AABB", "AAAA", "AAAA", NA, "AAAA", "AAAA", "AAAA",
"AAAA", "AAAA", "AAAA", "AAAA", "BBBB", NA, NA, NA, "AAAA", "AAAA",
NA, NA, NA, NA, "AAAA", NA, NA, NA, "AAAA", "BBBB", NA, NA, NA,
NA, "AABB", NA, NA, NA, "AABB", "AAAA", NA, NA, NA, NA, "AAAA",
"AAAA", "AAAA", "BBBB", "AAAA", "BBBB", "BBBB", "BBBB", "BBBB",
"BBBB", "AABB", "AABB", "AABB", "AAAA", "AABB", "AAAA", "AABB",
"AAAA", "AAAA", "AAAB", "BBBB", "BBBB", NA, "AABB", "AABB", "AABB",
"AABB", "AABB", "AABB", "AABB", "AAAA", "AAAA", NA, "AAAA", "AAAA",
"AAAA", "AAAA", "AAAA", "AAAA", "AAAA", "BBBB", "BBBB", NA, "BBBB",
"BBBB", "AAAA", "AAAA", "BBBB", "BBBB", "ABBB"), .Dim = c(10L, 10L))
的數據集我想在每個計算「A」。我嘗試了2種方法。
str_count
stringr
包裝。
> apply(aa,2,str_count,"A")
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 2 4 0 4 2 4 2 0 4 0
[2,] 2 4 1 1 1 4 2 0 4 0
[3,] 1 1 1 1 1 4 2 1 1 1
[4,] 2 4 1 1 1 0 4 2 4 0
[5,] 2 4 4 4 2 4 2 2 4 0
[6,] 2 4 4 0 4 0 4 2 4 4
[7,] 2 4 1 1 1 0 2 2 4 4
[8,] 2 4 1 1 1 0 4 2 4 0
[9,] 2 4 1 1 1 0 4 2 4 0
[10,] 2 4 1 1 1 0 3 2 4 1
這裏我得到1
的缺失。但我喜歡有NA
和regex
dosage<-function(string,char){
x<-sapply(regmatches(string, gregexpr(char, string)), length)
return(x)
}
apply(aa,2,dosage,"A")
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 2 4 0 4 2 4 2 0 4 0
[2,] 2 4 0 0 0 4 2 0 4 0
[3,] 0 0 0 0 0 4 2 0 0 0
[4,] 2 4 0 0 0 0 4 2 4 0
[5,] 2 4 4 4 2 4 2 2 4 0
[6,] 2 4 4 0 4 0 4 2 4 4
[7,] 2 4 0 0 0 0 2 2 4 4
[8,] 2 4 0 0 0 0 4 2 4 0
[9,] 2 4 0 0 0 0 4 2 4 0
[10,] 2 4 0 0 0 0 3 2 4 1
在這裏我得到0
,但我又喜歡有NA
。
我該怎麼做?
你可以只更換'回報(X)'和'ifelse(is.na(串),NA,X)'和'的功能dosage'將工作,只要你想 – rawr
@rawr是的,這個工作... – Ananta
你的'apply'函數給了我預期的輸出 – Jaap