[英]r - dplyr: counting the frequency of unique values in one variable for each unique value of another variable in the same data frame
[英]Using aggregate in R to find unique values of one variable for the same value of another variable
我想在此數據框中應用聚合函數:
A <- data.frame(c(1:2,1:2,2),c("a","c","b","c","d"))
colnames(A) <- c("ola","hi")
A
> A
ola hi
1 1 a
2 2 c
3 1 b
4 2 c
5 2 d
獲得A的有序值A $ ola和相應的A $ hi唯一值,如下所示:
A <- data.frame(c(1:2),c("a,b","c,d"))
colnames(A) <- c("ola","hi")
> A
ola hi
1 1 a,b
2 2 c,d
我試過這段代碼:
aggregate(A, by=list(A$ola), FUN=unique)
但它給出了這樣的結果:
Group.1 ola hi.1 hi.2
1 1 1 a b
2 2 2 c d
可以請有人解釋我,我做錯了什么?
除了paste
方法,如果我們想要'hi'列作為list
,
r1 <- aggregate(hi~ola, unique(A), FUN=list)
r1
# ola hi
#1 1 a, b
#2 2 c, d
OP的代碼提供了data.frame
r2 <- aggregate(hi~ola, A, FUN=unique)
r2
# ola hi.1 hi.2
#1 1 a b
#2 2 c d
有兩列,第二列'hi'是一個matrix
。
str(r2)
#'data.frame': 2 obs. of 2 variables:
#$ ola: int 1 2
#$ hi : chr [1:2, 1:2] "a" "c" "b" "d"
另外一個選項:
library(dplyr)
distinct(A) %>% group_by(ola) %>% summarise(hi = toString(hi))
這使:
#Source: local data frame [2 x 2]
#
# ola hi
# (int) (chr)
#1 1 a, b
#2 2 c
數據
A <- structure(list(ola = c(1L, 2L, 1L, 2L), hi = structure(c(1L,
3L, 2L, 3L), .Label = c("a", "b", "c"), class = "factor")), .Names = c("ola",
"hi"), row.names = c(NA, -4L), class = "data.frame")
如果你真的想要一個包含獨特項目文本的列,你只需要更復雜的功能。
uniqCSV <- function(x) { paste(unique(x), sep = ',') }
aggregate(hi ~ ola, data = A, FUN= uniqCSV)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.