R-函数中的交叉引用变量
我有一个由给定的帧dbR-函数中的交叉引用变量,r,R,我有一个由给定的帧db > A <- c(0,1,2,3,0,1) > B <-c('NA','NA','NA','NA','NA','NA') > C <- c('Fnord', 'Fnord','Applebees','Pumpkin','Applebees','Pumpkin') > db <- data.frame(A,B,C) 到目前为止,我在这方面的尝试都失败了。如果之前有人回答过,我道歉-我的搜索引擎没有给我答案 我尝试过的一个例子
> A <- c(0,1,2,3,0,1)
> B <-c('NA','NA','NA','NA','NA','NA')
> C <- c('Fnord', 'Fnord','Applebees','Pumpkin','Applebees','Pumpkin')
> db <- data.frame(A,B,C)
到目前为止,我在这方面的尝试都失败了。如果之前有人回答过,我道歉-我的搜索引擎没有给我答案
我尝试过的一个例子是
db$D <- sapply(db$C, FUN=function(x) {return(sum(db$A %in% subset(db, C="x")))})
db$B <- db$D - db$A
db$D这将创建与您的描述匹配的数据帧:
db <- rbind(db, structure(list(A = 2:3, B = c(0L, 3L), C = structure(2:3, .Label = c("Applebees",
"Fnord", "Fnord2", "Pumpkin"), class = "factor")), .Names = c("A",
"B", "C"), row.names = c("7", "8"), class = "data.frame") )
# Then just merge with itself and remove the cases where the C values are '=='
mdb <- merge(db,db, by="A")
mdb[mdb$C.x != mdb$C.y, c('A', 'C.y', 'C.x')]
A C.y C.x
2 0 Applebees Fnord
3 0 Fnord Applebees
6 1 Pumpkin Fnord
7 1 Fnord Pumpkin
10 2 Fnord Applebees
11 2 Applebees Fnord
14 3 Fnord2 Pumpkin
15 3 Pumpkin Fnord2
db请显示您所做的尝试,即使失败。这将帮助我们更容易地回答您的问题。如果您愿意,我可以发布一堆写得很糟糕的黑客代码。一种尝试是使用一组for(在%1:6中为j%)和for(在%1:6中为k%)循环,这对于较大的数据帧来说似乎效率很低。使用switch()或idential()之类的东西似乎更好。我不知道如何在不使用索引循环的情况下使用后者。显然,相同(db$C,db$C)并没有太大帮助。我不确定这是否适用于我的目的,但它确实帮助我解决了一个不相关的问题。谢谢
db <- rbind(db, structure(list(A = 2:3, B = c(0L, 3L), C = structure(2:3, .Label = c("Applebees",
"Fnord", "Fnord2", "Pumpkin"), class = "factor")), .Names = c("A",
"B", "C"), row.names = c("7", "8"), class = "data.frame") )
# Then just merge with itself and remove the cases where the C values are '=='
mdb <- merge(db,db, by="A")
mdb[mdb$C.x != mdb$C.y, c('A', 'C.y', 'C.x')]
A C.y C.x
2 0 Applebees Fnord
3 0 Fnord Applebees
6 1 Pumpkin Fnord
7 1 Fnord Pumpkin
10 2 Fnord Applebees
11 2 Applebees Fnord
14 3 Fnord2 Pumpkin
15 3 Pumpkin Fnord2