user2952422 user2952422 - 1 month ago 9
R Question

R: How to paste value from table 1 into table 3 if value in table two is >0

I have two tables with three columns each. There are absolute numbers in table A and percentage values in table B.

I would like to create a third table in which values from table 1 are present if the value for this cell in table B is >0. Can I somehow do that with merge (x,y,...)?

#Table 1 (absolute numbers)
389
500
46
340
67

#Table 2 (percentage)
45
67
0
23
0

#Table 3
389
500
0
340
0

Answer

We create a logical index with the column from the second dataset and use that to replace the elements in the first dataset column to 0.

df3 <- df1
df3[,1][df2[,1]==0] <- 0 
df3
#   v1
#1 389
#2 500
#3   0
#4 340
#5   0

data

df1 <- structure(list(v1 = c(389L, 500L, 46L, 340L, 67L)), 
.Names = "v1", class = "data.frame", row.names = c(NA, 
 -5L))

df2 <- structure(list(v1 = c(45L, 67L, 0L, 23L, 0L)), .Names = "v1", 
class = "data.frame", row.names = c(NA, -5L))