基于组 ID 的匹配值
Matching values based on group ID
假设我有以下数据框(实际的数据框代表非常大的数据集)
df<- structure(list(x = c(1, 1, 1, 2, 2, 3, 3, 3), y = structure(c(1L,
6L, NA, 2L, 4L, 3L, 7L, 5L), .Label = c("all", "fall", "hello",
"hi", "me", "non", "you"), class = "factor"), z = structure(c(5L,
NA, 4L, 2L, 1L, 6L, 3L, 4L), .Label = c("fall", "hi", "me", "mom",
"non", "you"), class = "factor")), .Names = c("x", "y", "z"), row.names = c(NA,
-8L), class = "data.frame")
看起来像
>df
x y z
1 1 all non
2 1 non <NA>
3 1 <NA> mom
4 2 fall hi
5 2 hi fall
6 3 hello you
7 3 you me
8 3 me mom
我想做的是计算每组 x
(1,2 或 3)中匹配值的数量。例如,组号 1
有一个匹配值是 "non"
(NA 应该被忽略)。所需的输出如下所示:
x n
1 1 1
2 2 2
3 3 2
尝试以一种方式思考而不是 for-loop
因为我有一个很大的数据集但找不到我的方法。
使用 dplyr
:
library(dplyr)
df %>% group_by(x) %>%
summarise(n = sum(y %in% na.omit(z)))
do.call(rbind,by(df,df$x,function(g) c(x=g$x[1],n=sum(!is.na(match(g$y,g$z,inc=NA))))));
## x n
## 1 1 1
## 2 2 2
## 3 3 2
只是为了晚上的乐趣,我尝试了一个基本的 R 解决方案,当然它非常丑陋。
ind <- by(df, df$x, function(x) which(na.omit(x[["y"]]) %in% na.omit(df[["z"]])))
sm <- lapply(ind, length)
cbind(unique(df$x), sm)
sm
1 1 1
2 2 2
3 3 2
另一种基本 R 方法,代码更少(我希望丑陋程度更低):
ind <- by(df, df$x, function(x) sum(na.omit(x[["y"]]) %in% na.omit(x[["z"]])))
cbind(unique(df$x), ind)
ind
1 1 1
2 2 2
3 3 2
假设我有以下数据框(实际的数据框代表非常大的数据集)
df<- structure(list(x = c(1, 1, 1, 2, 2, 3, 3, 3), y = structure(c(1L,
6L, NA, 2L, 4L, 3L, 7L, 5L), .Label = c("all", "fall", "hello",
"hi", "me", "non", "you"), class = "factor"), z = structure(c(5L,
NA, 4L, 2L, 1L, 6L, 3L, 4L), .Label = c("fall", "hi", "me", "mom",
"non", "you"), class = "factor")), .Names = c("x", "y", "z"), row.names = c(NA,
-8L), class = "data.frame")
看起来像
>df
x y z
1 1 all non
2 1 non <NA>
3 1 <NA> mom
4 2 fall hi
5 2 hi fall
6 3 hello you
7 3 you me
8 3 me mom
我想做的是计算每组 x
(1,2 或 3)中匹配值的数量。例如,组号 1
有一个匹配值是 "non"
(NA 应该被忽略)。所需的输出如下所示:
x n
1 1 1
2 2 2
3 3 2
尝试以一种方式思考而不是 for-loop
因为我有一个很大的数据集但找不到我的方法。
使用 dplyr
:
library(dplyr)
df %>% group_by(x) %>%
summarise(n = sum(y %in% na.omit(z)))
do.call(rbind,by(df,df$x,function(g) c(x=g$x[1],n=sum(!is.na(match(g$y,g$z,inc=NA))))));
## x n
## 1 1 1
## 2 2 2
## 3 3 2
只是为了晚上的乐趣,我尝试了一个基本的 R 解决方案,当然它非常丑陋。
ind <- by(df, df$x, function(x) which(na.omit(x[["y"]]) %in% na.omit(df[["z"]])))
sm <- lapply(ind, length)
cbind(unique(df$x), sm)
sm
1 1 1
2 2 2
3 3 2
另一种基本 R 方法,代码更少(我希望丑陋程度更低):
ind <- by(df, df$x, function(x) sum(na.omit(x[["y"]]) %in% na.omit(x[["z"]])))
cbind(unique(df$x), ind)
ind
1 1 1
2 2 2
3 3 2