R中重复2次或更多次的变量数 [英] the number of variables that are repeated 2 or more times in R

查看:53
本文介绍了R中重复2次或更多次的变量数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种形式的数据:list(即r)和data.frame(即df).对于每种形式的数据,我如何知道 重复两次或两次以上 的变量数量(在下面的示例中,我的所需输出 >是:AA 3 timesBB 2 timesCC 2 times)?

I have two forms of data: a list (i.e., r) and a data.frame (i.e., df). For each form of data, how can I know the number of variables that are repeated 2 or more times (in the example below, my desired output is: AA 3 times, BB 2 times, CC 2 times)?

注意:无论数据形式如何,答案都应该相同.

NOTE: the answer regardless of the form of data, should be the same.

r <- list( data.frame( AA = c(2,2,1,1,NA, NA), BB = c(1,1,1,2,2,NA), CC = c(1:5, NA)), # LIST

        data.frame( AA = c(1,NA,3,1,NA,NA), DD = c(1,1,1,2,NA,NA)),

        data.frame( AA = c(1,NA,3,1,NA,NA), BB = c(1,1,1,2,2,NA), CC = c(0:4, NA)) )


df <- do.call(cbind, r)       ## DATA.FRAME

推荐答案

我们可以在数据集的names上使用>= 2创建频率计数

We can create a frequency count with >= 2 on the names of the dataset,

tbl <- table(names(df))
tbl1 <- tbl[tbl >=2]
tbl1
#  AA BB CC 
#  3  2  2 

lapply(r, function(x) table(names(x)[names(x) %in% names(tbl1)]))


如果我们需要其他答案


If we need it from another answer

vec <- names(unlist(r, recursive = FALSE))
nm1 <- unique(vec[duplicated(vec)])
lapply(r, function(x) table(names(x)[names(x) %in% nm1]))

这篇关于R中重复2次或更多次的变量数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆