我希望找到在一个组中有多个值的变量--即依赖于(或不依赖)分组变量的变量。
换句话说,例如使用具有以下信息的数据帧
(1)依赖于公司(例如“行业”)或
(2)取决于公司年度(例如“年销售额”),
我希望能够辨别哪些变量属于类型(1),哪些属于类型(2)。
sample_df <-
data.frame(
year = rep(2013:2015, 3),
firm = rep(c("Disney", "Netflix", "Hulu"), each = 3),
infoA = c(rep(1, 6), rep(2, 3)),
infoB = c(c(1:3), rep(2, 6)),
infoC = rep(3:1, each = 3)
)
# year firm infoA infoB infoC
# 2013 Disney 1 1 3
# 2014 Disney 1 2 3
# 2015 Disney 1 3 3
# 2013 Netflix 1 2 2
# 2014 Netflix 1 2 2
# 2015 Netflix 1 2 2
# 2013 Hulu 2 2 1
# 2014 Hulu 2 2 1
# 2015 Hulu 2 2 1
如果分组变量是'firm',
(1)列'infoA‘和'infoC’在每个组内不变,
(2)虽然“year”和“infoB”在每个组中会有所不同,
在有许多列的环境中,实现这种划分的最简单方法是什么?
发布于 2021-01-15 07:04:36
我们可以编写一个函数来计算每个组的唯一值的数量。如果值有变化,则返回TRUE
或FALSE
。
library(dplyr)
check_dependability <- function(data, col1, col2 = NULL) {
data %>%
group_by({{col1}}, {{col2}}) %>%
summarise(across(.fns = ~n_distinct(.) > 1))
}
check_dependability(sample_df, firm)
# firm year infoA infoB infoC
# <chr> <lgl> <lgl> <lgl> <lgl>
#1 Disney TRUE FALSE TRUE FALSE
#2 Hulu TRUE FALSE FALSE FALSE
#3 Netflix TRUE FALSE FALSE FALSE
check_dependability(sample_df, firm, year)
# firm year infoA infoB infoC
# <chr> <int> <lgl> <lgl> <lgl>
#1 Disney 2013 FALSE FALSE FALSE
#2 Disney 2014 FALSE FALSE FALSE
#3 Disney 2015 FALSE FALSE FALSE
#4 Hulu 2013 FALSE FALSE FALSE
#5 Hulu 2014 FALSE FALSE FALSE
#6 Hulu 2015 FALSE FALSE FALSE
#7 Netflix 2013 FALSE FALSE FALSE
#8 Netflix 2014 FALSE FALSE FALSE
#9 Netflix 2015 FALSE FALSE FALSE
发布于 2021-01-15 06:43:29
根据groupnig变量进行分组,并计算不同项的数量,如果它们都相同,则返回0或1
res=aggregate(
subset(sample_df,select=-c(firm)),
list(sample_df$firm),
function(x){
if (length(table(x))==1){
0
} else {
1
}
}
)
Group.1 year infoA infoB infoC
1 Disney 1 0 1 0
2 Hulu 1 0 0 0
3 Netflix 1 0 0 0
要找出哪些列与分组变量不同,只需按列求和
colSums(subset(res,select=-c(Group.1)))==0
year infoA infoB infoC
FALSE TRUE FALSE TRUE
https://stackoverflow.com/questions/65731506
复制相似问题