R 比较每个组中变量的每个元素
考虑R中的数据帧:R 比较每个组中变量的每个元素,r,R,考虑R中的数据帧: set.seed(36) y <- runif(10,0,200) group <- sample(rep(1:2, each=5)) d <- data.frame(y, group) 但是,当我在一个函数中执行此操作时,组的数量会发生变化(group将是该函数的参数),那么我不能以这种方式继续。如何优雅地编写最后三行代码,将各组中的所有y与所有y进行比较 library(data.table) setDT(d)[, as.data.table(out
set.seed(36)
y <- runif(10,0,200)
group <- sample(rep(1:2, each=5))
d <- data.frame(y, group)
但是,当我在一个函数中执行此操作时,组的数量会发生变化(
group
将是该函数的参数),那么我不能以这种方式继续。如何优雅地编写最后三行代码,将各组中的所有y
与所有y
进行比较
library(data.table)
setDT(d)[, as.data.table(outer(y, y, "<=")), group]
# group V1 V2 V3 V4 V5
#1: 1 TRUE TRUE FALSE FALSE FALSE
#2: 1 FALSE TRUE FALSE FALSE FALSE
#3: 1 TRUE TRUE TRUE FALSE TRUE
#4: 1 TRUE TRUE TRUE TRUE TRUE
#5: 1 TRUE TRUE FALSE FALSE TRUE
#6: 2 TRUE TRUE FALSE TRUE FALSE
#7: 2 FALSE TRUE FALSE TRUE FALSE
#8: 2 TRUE TRUE TRUE TRUE TRUE
#9: 2 FALSE FALSE FALSE TRUE FALSE
#10: 2 TRUE TRUE FALSE TRUE TRUE
要对多个组执行相同的操作,我们可以使用
lappy
并对每个组执行outer
操作
lapply(split(d, d$group), function(x) outer(x[["y"]], x[["y"]], "<="))
#$`1`
# [,1] [,2] [,3] [,4] [,5]
#[1,] TRUE TRUE FALSE FALSE FALSE
#[2,] FALSE TRUE FALSE FALSE FALSE
#[3,] TRUE TRUE TRUE FALSE TRUE
#[4,] TRUE TRUE TRUE TRUE TRUE
#[5,] TRUE TRUE FALSE FALSE TRUE
#$`2`
# [,1] [,2] [,3] [,4] [,5]
#[1,] TRUE TRUE FALSE TRUE FALSE
#[2,] FALSE TRUE FALSE TRUE FALSE
#[3,] TRUE TRUE TRUE TRUE TRUE
#[4,] FALSE FALSE FALSE TRUE FALSE
#[5,] TRUE TRUE FALSE TRUE TRUE
lappy(split(d,d$group),function(x)outer(x[[“y”]],x[“y”],“将最后三行转换为lappy(split(d,d$group),function(x)outer(x[“y”]],x[“y”]],”@RonakShah谢谢你。你能告诉我setDT(d)[,as.data.table(outer)(y,y,“@Leaf你的意思是setDT(d)[,as.data.table)(outer)(y,y),”好的,它正在工作。但我实际上正在尝试这样做:dt1@Leaf你想在哪里更新?是在'dt1'还是'dt2'?@Leaf如果你正在更新'dt1',那么for(j in 2:ncol(dt1)){set(dt1,I=NULL,j=j,value=dt1[[j]]*dt2[[j]])}
setDT(d)[, CJ(y, y), group][, V1 <= V2, group]
lapply(split(d, d$group), function(x) outer(x[["y"]], x[["y"]], "<="))
#$`1`
# [,1] [,2] [,3] [,4] [,5]
#[1,] TRUE TRUE FALSE FALSE FALSE
#[2,] FALSE TRUE FALSE FALSE FALSE
#[3,] TRUE TRUE TRUE FALSE TRUE
#[4,] TRUE TRUE TRUE TRUE TRUE
#[5,] TRUE TRUE FALSE FALSE TRUE
#$`2`
# [,1] [,2] [,3] [,4] [,5]
#[1,] TRUE TRUE FALSE TRUE FALSE
#[2,] FALSE TRUE FALSE TRUE FALSE
#[3,] TRUE TRUE TRUE TRUE TRUE
#[4,] FALSE FALSE FALSE TRUE FALSE
#[5,] TRUE TRUE FALSE TRUE TRUE