我有一个主数据集(all_members)。它每人有一排。我有25个其他数据表,成员可能会或可能不会列出,1次以上。我正在使用R Studio。
我想在all_members上为每个附加数据表创建一个新变量,然后执行一个countif,计算成员为其他数据表中的每个变量显示的次数。
在excel中,我会做一个组合vlookup + countif。如何在R Studio中完成此操作?
答案 0 :(得分:0)
有几种方法可以做到这一点,但这取决于您的数据是什么样的。可以简单地将所有表连接到单个数据帧中,只需:
library(dplyr)
df %>% group_by(name) %>% tally()
如果由于数据不同而无法将数据合并为单个df,则会更复杂一些。
答案 1 :(得分:0)
以下答案依赖于我制作的可重现数据,该数据计算特定班级的学生人数。这些计数作为新列添加到主数据集,名为all.students
。
在sum()
内的匿名函数中使用sapply()
非常灵活,因此它会计算在不同数据集中多次出现的ID
个值。虽然math.class
和history.class
每个数据集只有一个唯一的学生,但detention
多次包含同一个学生。这些计数反映在最终输出中。
此可重现的示例可确保all.student$ID
中的值是唯一的。
此答案依赖于手动创建(和命名)并列出其他表中的单独ID
列。在计算每个表中X
个体学生出现的次数时,您可以将该列表用作all.students
参数。使用cbind.data.frame()
列将all.students
与count.ID.in.other.tables
绑定,将这些计数作为列添加到all.students
。
# create data
all.students <-
data.frame( ID = 1:10
, Gender = sample( x = c( "F", "M"), size = 10, replace = TRUE )
, stringsAsFactors = FALSE
)
# ensure all.students
# only contains one row for each unique value in `ID` column
all.students <-
all.students[ which( !duplicated( x = all.students$ID ) ) , ]
# check dim
dim( all.students )
# [1] 10 2
# three data frames
# one for each class
math.class <-
data.frame( ID = c( 2:4, 6:7)
, Grade = c( "A", "B", "C", "A", "C" )
, stringsAsFactors = FALSE
)
history.class <-
data.frame( ID = c( 1, 8:10)
, Grade = rep( x = "A", times = 4 )
, stringsAsFactors = FALSE
)
detention <-
data.frame( ID = rep( x = 5, times = 3)
, Date = as.Date( x = c( "2017-12-01"
, "2018-01-23"
, "2018-02-14"
)
)
, stringsAsFactors = FALSE
)
# create list
# containing each `ID` column
# from each table not named `all.students`
ID.in.other.table <-
list( detention = detention$ID
, history.class = history.class$ID
, math.class = math.class$ID
)
# view list
ID.in.other.table
# $detention
# [1] 5 5 5
#
# $history.class
# [1] 1 8 9 10
#
# $math.class
# [1] 2 3 4 6 7
# count how many times each member
# appears in the other data frames
count.ID.in.other.tables <-
lapply( X = ID.in.other.table
, FUN = function( i )
sapply( X = all.students$ID,
FUN = function( j )
sum( i == j )
)
)
# view list
count.ID.in.other.tables
# $detention
# [1] 0 0 0 0 3 0 0 0 0 0
#
# $history.class
# [1] 1 0 0 0 0 0 0 1 1 1
#
# $math.class
# [1] 0 1 1 1 0 1 1 0 0 0
# combine vectors in list
# and add to all.students
all.students <-
cbind.data.frame(
all.students
, do.call(
what = cbind
, args = count.ID.in.other.tables
)
, stringsAsFactors = FALSE
)
# check dim
dim( all.students ) # [1] 10 5
# view data
all.students
# ID Gender detention history.class math.class
# 1 1 F 0 1 0
# 2 2 M 0 0 1
# 3 3 M 0 0 1
# 4 4 M 0 0 1
# 5 5 F 3 0 0
# 6 6 F 0 0 1
# 7 7 M 0 0 1
# 8 8 F 0 1 0
# 9 9 F 0 1 0
# 10 10 M 0 1 0
# end of script #