Reputation: 4227
I have to generate data via sampling process and apply a function.
p = 10; f = 8
set.seed (123)
pars <- data.frame (id = 1:p,
value = sample (c("AA", "AB", "AB", "BB"),p, replace = TRUE))
pars
id value
1 1 AB
2 2 BB
3 3 AB
4 4 BB
5 5 BB
6 6 AA
7 7 AB
8 8 BB
9 9 AB
10 10 AB
fdat <- data.frame (t(combn(pars$id,2)))
set.seed (1234)
sdf <- fdat[sample(1:nrow(fdat), f),]
names (sdf) <- c("P1", "P2")
sdf
P1 P2
6 1 7
28 4 8
27 4 7
43 8 9
36 6 7
26 4 6
1 1 2
9 1 10
Value for each combination to be applied is in the table pars. For example for first P1 and P2 combination 1 = "AB", 7 = "AB". For second, 4 = "BB", 8 = "BB".
Now I want to apply the following function to sdf (considering the value in pars table). P2.v is value of P1, P2.v is value of P2.
genofun <- function (P1.v, P2.v, n) {
if (P1.v == "AA" & P2.v == "BB" ) {
CLD <- rep ("AB", n)
}
if (P1.v == "BB" & P2.v == "AA" ) {
CLD <- rep ("AB", n)
}
if (P1.v == "AA" & P2.v == "AB") {
CLD <- sample (c("AA", "AB"), n, replace = TRUE)
}
if (P1.v == "AB" & P2.v == "AA") {
CLD <- sample (c("AA", "AB"), n, replace = TRUE)
}
if (P1.v == "BB" & P2.v == "AB") {
CLD <- sample (c("BB", "AB"), n, replace = TRUE)
}
if ( P1.v == "AB" & P2.v == "BB") {
CLD <- sample (c("BB", "AB"), n, replace = TRUE)
}
if (P1.v == "BB" & P2.v == "BB") {
CLD <- rep("BB", n, replace = TRUE)
}
if (P1.v == "AA" & P2.v == "AA") {
CLD <- rep("AA", n)
}
if (P1.v == "AB" & P2.v == "AB") {
CLD <- sample(c("AA", "AB","AB", "BB"), n, replace = TRUE)
}
out <- c(P1.v, P2.v, CLD)
return (out)
}
n = 5
genofun (P1, P2, n)
Thus expected output would be :
P1 P2 P1.v P2.v CLD1 CLD2 CLD3 CLD4 CLD5 <- (essentially number columns = n)
6 1 7
28 4 8
27 4 7
43 8 9
36 6 7
26 4 6
1 1 2
9 1 10
Upvotes: 1
Views: 191
Reputation: 7475
Currently there appears to be an error in the definition of genofun
but once that is fixed the following should work:
P1v<-as.character(pars$value[sdf$P1])
P2v<-as.character(pars$value[sdf$P2])
dum<-cbind(sdf,t(mapply(genofun,P1.v=P1v,P2.v=P2v,n=5)))
names(dum)<-c('P1','P2','P1.v','P2.v','CLD1','CLD2','CLD3','CLD4','CLD5')
> dum
P1 P2 P1.v P2.v CLD1 CLD2 CLD3 CLD4 CLD5
6 1 7 AB AB AA AB AB AB AA
28 4 8 BB BB BB BB BB BB BB
27 4 7 BB AB AB BB AB BB AB
43 8 9 BB AB AB BB BB BB AB
36 6 7 AA AB AB AA AA AB AA
26 4 6 BB AA AB AB AB AB AB
1 1 2 AB BB AB AB AB AB AB
9 1 10 AB AB AB BB AA AB AB
>
Upvotes: 2