简体   繁体   English

如何识别数据框中相对于其他数据框的唯一列?

[英]How to identify unique columns in a data frame with respect to other data frames?

If I have several data frames, how can I identify the columns which are unique to a certain data frame?如果我有多个数据框,如何识别特定数据框所独有的列?

df1 <- data.frame(A=rnorm(5), B=rnorm(5), C=rnorm(5))
df2 <- data.frame(B=rnorm(5), C=rnorm(5), D=rnorm(5))
df3 <- data.frame(B=rnorm(5), C=rnorm(5), D=rnorm(5))

What I want to achieve is something like the unique() function, that gives me the unique columns in a data frame with respect to other data frames.我想要实现的是类似于 unique() 函数的功能,它为我提供了数据框中相对于其他数据框的唯一列。

unique.columns(df1, c(df2, df3))
[1] "A"

but

unique.columns(df2, c(df1, df3))
[1] NA

since there are no unique columns in df2.因为 df2 中没有唯一的列。

You could use Reduce along with setdiff to deal with any number of comparison datasets easily.您可以使用Reducesetdiff处理任意数量的比较数据集。 The first named dataset will be compared to the remainder.第一个命名的数据集将与其余数据集进行比较。

Reduce(setdiff, lapply(list(df1,df2,df3), names))
#[1] "A"

Reduce(setdiff, lapply(list(df2,df1,df3), names))
#character(0)

We can use setdiff and union我们可以使用setdiffunion

unique.columns <- function(df1, df2, df3) {
   setdiff(names(df1), union(names(df2), names(df3)))
}

unique.columns(df1, df2, df3)
#[1] "A"

unique.columns(df2, df1, df3)
#character(0)

If you are going to pass a variable number of dataframes to the function, you can change the function如果要将可变数量的数据帧传递给函数,则可以更改函数

unique.columns <- function(df1, ...) {
   temp <- list(...)
   setdiff(names(df1), unique(c(sapply(temp, names))))
}

unique.columns(df1, df3)
#[1] "A"

You could also use the "not in" using !你也可以使用“不在”使用! and %in% on the colnames of each df to get the column names that are unique to one df in comparison with other dfs.%in%在每个 df 的colnames上获取一个 df 与其他 df 相比唯一的列名。

colnames(df1)[!(colnames(df1) %in% c(colnames(df2),colnames(df3)))]
#[1] "A"
colnames(df2)[!(colnames(df2) %in% c(colnames(df1),colnames(df3)))]
#character(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM