R循环列以计算在不同子集中具有级别的行数 [英] R loop over columns to calculate the number of rows that have levels in a different subset

查看:64
本文介绍了R循环列以计算在不同子集中具有级别的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

> x <- data.table( C1=c('a','b','c','d') )
> y <- data.table( C1=c('a','b','b','a') )
> f="C1"
> x[ C1 %in% unique(y$C1),]
   C1
1:  a
2:  b

,所以我可以看到y $ C1的级别覆盖了x $ C1的2行。

so I can see that the levels of y$C1 cover 2 rows for x$C1.

> y[ C1 %in% unique(x$C1),]
   C1
1:  a
2:  b
3:  b
4:  a

,所以我可以看到x $ C1的级别覆盖了4行y $ C1。

so I can see that the levels of x$C1 cover 4 rows for y$C1.

这样可以工作,但是我想为列名使用一个变量,这样当有很多列时我可以构建一个循环。
以下不工作:

This works, but I would like to use a variable for the column name so that I can build a loop when there are many columns. The following does not work:

> y[ f %in% unique(x$C1),]
Empty data.table (0 rows) of 1 col: C1


推荐答案

您也可以使用:

 f <- quote(C1)
 y[ eval(f) %in% unique(x$C1),]
 #    C1
 #1:  a
 #2:  b
 #3:  b
 #4:  a

这篇关于R循环列以计算在不同子集中具有级别的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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