mikew - 1 year ago 63
R Question

# Extracting first column that meets certain criteria for each row

I will try to explain what I am doing the best I can it is kind of confusing but I'll give it a shot. Essentially I start with 2 data frames. Each one containing a unique row per person and two items per user as columns. My goal is to turn this into 1 data frame with one unique row per user and the first item from each of the two data frames upon the condition that the items do not repeat. For example if for customer 1 in the first data frame his items are "a" and "d" and in the second data frame his items are "a" and "c", I would want the final data frame to be "a" and "c" for this customer. I have written an apply that does this however when I perform this on roughly 160,000 rows it takes quite a bit of time. I was hoping someone would be able to come up with a more efficient solution to my problem.

``````d1 <- data.frame(id = c("1", "2", "3"), stringsAsFactors = F)
r1 <- data.frame(i1 = c("a", "b", "c"), i2 = c("d", "e", "f"), stringsAsFactors = F)
rownames(r1) = d1\$id
r2 <- data.frame(i1 = c("a", "c", "f"), i2 = c("c", "t", "l"), stringsAsFactors = F)
rownames(r2) = d1\$id

dFinal <- data.frame(id = d1\$id, r1 = "", r2 = "", stringsAsFactors = F)

dFinal\$r1 = apply(dFinal, 1, function(x){r1[rownames(r1) == x["id"], "i1"]})
dFinal\$r2 = apply(dFinal, 1, function(x){r2[rownames(r2) == x["id"], which(!r2[rownames(r2) == x["id"],c("i1","i2")] %in% x["r1"])[1]]})
``````

Answer Source

Would the following do what you're looking for:

``````# Keep only first column of first data.frame
df <- cbind(d1,r1,r2)[,-3]
names(df) <- c("id","r1_final","r2_i1","r2_i2")
df\$r2_final <- df\$r2_i1

# Keep only second column of second data.frame
# if the value in the first column is found in first data.frame
df[df\$r1_final == df\$r2_i1,"r2_final"] <- df[df\$r1_final == df\$r2_i1,"r2_i2"]
df_final <- df[,c("id","r1_final","r2_final")]
print(df_final)

id r1_final r2_final
1  1        a        c
2  2        b        c
3  3        c        f
``````

Edit: OP asked for a solution if there were four data.frames instead of 2 like in the example, here is some code that I haven't tested but it should work with two additional columns

``````df\$r2_final <- df\$r2_i1
df\$r3_final <- df\$r3_i1
df\$r4_final <- df\$r4_i1

df[df\$r1_final == df\$r2_i1,"r2_final"] <- df[df\$r1_final == df\$r2_i1,"r2_i2"]
df[df\$r3_i1 %in% c(df\$r1_final,df\$r2_final),"r3_final"] <- df[df\$r3_i1 %in% c(df\$r1_final,df\$r2_final),"r3_i2"]
df[df\$r4_i1 %in% c(df\$r1_final,df\$r2_final,df\$r3_final),"r4_final"] <- df[df\$r4_i1 %in% c(df\$r1_final,df\$r2_final,df\$r3_final),"r4_i2"]
df_final <- df[,c("id","r1_final","r2_final","r3_final","r4_final")]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download