Ernie
Ernie

Reputation: 1153

Using rbind.fill does not fill the correct value

I don’t understand how rbind.fill works, I guess. I have a data frame called main.df:

     TLT PCY SHY VTI TIP VNQ VWO RWX VEA DBC GLD
Pct   0   0   0   0   0   0   0   0   0   0   0

I want to bind the following different-sized data frame named p.df to it:

          VWO       VEA       VTI
Pct 0.3333333 0.3333333 0.3333333

When I execute rbind.fill(main.df, p.df) I get:

  TLT PCY SHY VTI TIP VNQ VWO RWX VEA DBC GLD
1   0   0   0   0   0   0   0   0   0   0   0
2  NA  NA  NA   1  NA  NA   1  NA   1  NA  NA

which is not what I want. I expected to get:

  TLT PCY SHY VTI     TIP VNQ  VWO     RWX VEA    DBC GLD
1   0   0   0   0       0   0    0       0   0     0   0 
2  NA  NA  NA   0.333   NA  NA   0.333  NA  0.333  NA  NA

How do I do this? The dput of my objects are below.

main.df <- structure(list(
  TLT = 0, PCY = 0, SHY = 0, VTI = 0, TIP = 0, VNQ = 0, VWO = 0, RWX = 0, VEA = 0, DBC = 0, GLD = 0),
  .Names = c("TLT", "PCY", "SHY", "VTI", "TIP", "VNQ", "VWO", "RWX", "VEA", "DBC", "GLD"),
  row.names = "Pct", class = "data.frame")

p.df <- structure(list(
  VWO = structure(1L, .Names = "Pct", .Label = c("0.3333333", "VWO"), class = "factor"),
  VEA = structure(1L, .Names = "Pct", .Label = c("0.3333333", "VEA"), class = "factor"),
  VTI = structure(1L, .Names = "Pct", .Label = c("0.3333333", "VTI"), class = "factor")),
  .Names = c("VWO", "VEA", "VTI"), row.names = "Pct", class = "data.frame")

Upvotes: 1

Views: 311

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176688

It would help if you provided a reproducible example using dput(main.df) and dput(p.df), but it appears that one or both of those objects contain factor vectors, not numeric vectors. So you need to convert them.

main.df[] <- lapply(main.df, function(f) as.numeric(levels(f))[f])
p.df[] <- lapply(p.df, function(f) as.numeric(levels(f))[f])

See How to convert a factor to an integer\numeric without a loss of information for details.

Upvotes: 2

Related Questions