[英]Concatenating with the aggregate function in R
我已經獲得了一個數據,需要根據特定的條件進行合並/匯總。 我知道如何對數字變量執行此操作,但是這一次,我需要從字符串向量中計算出一些內容,例如,我有:
V1 V2
1 YYY
1 MMMMMM
1 UUUU
2 YY
2 UUU
.
.
.
我正在嘗試計算特定V1上的MU%,因此我的結果集如下所示:
V1 V2
1 75%
2 60%
我一直在擺弄聚合函數,但是我至少不能粘貼它來粘貼V1中的所有數據,所以
aggregate(V1~V2, data=x,FUN=paste(x))
顯然對我不起作用。
這是dplyr
和stringr
解決方案
## Create the sample data
dat <- read.table(text = "V1 V2
1 YYY
1 MMMMMM
1 UUUU
2 YY
2 UUU", header = TRUE, stringsAsFactors = FALSE)
## Load the packages
library("dplyr")
library("stringr")
對於V1
每個組,計算字符總數中M和U的數目:
dat %>%
group_by(V1) %>%
summarize(V2 = sum(str_count(V2, "M|U")) / sum(nchar(V2)))
## Source: local data frame [2 x 2]
## V1 V2
## (int) (dbl)
## 1 1 0.7692308
## 2 2 0.6000000
這是直接來自原始數據集的方法:
library(stringi)
stack(
tapply(d$V2, d$V1,
function(ii) sum(stri_count_regex(ii, "M|U")) /
sum(stri_count_regex(ii, "."))))
# values ind
#1 0.7692308 1
#2 0.6000000 2
要使用聚合語句,您只需要進行一些更改:
d2 <- aggregate(V2 ~ V1, data=d, function(ii) paste0(ii, collapse=""))
# no packages used in this solution:
d2$V2 <-
sapply(
strsplit(d2$V2, "", perl=TRUE),
function(ii) sum(grepl("M|U", ii))/length(ii))
# V1 V2
#1 1 0.7692308
#2 2 0.6000000
或使用stringi
包中的stri_count
函數,有一個更好的簡短選擇:
d2 <- aggregate(V2~V1, data=d, function(ii) paste0(ii, collapse=""))
library(stringi)
d2$V2 <- stri_count_regex(d2$V2, "M|U") / nchar(d2$V2)
# V1 V2
#1 1 0.7692308
#2 2 0.6000000
data.table
的選項
library(data.table)
setDT(dat)[, list(V2=sum(nchar(V2)-nchar(gsub("M|U", "",
V2)))/sum(nchar(V2))), V1]
# V1 V2
#1: 1 0.7692308
#2: 2 0.6000000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.