0

I have three columns from three different files. I want to merge these three columns in a new data frame. To do that, I did the following:

  df1 <- read.csv("location of file1")
  df2 <- read.csv("location of file2")
  df3 <- read.csv("location of file3")
  dataset <- data.frame(B1_1=integer(), B1_2=integer(), B1_3=integer(), stringsAsFactors=FALSE)
  dataset$B1_1 <- df1$Rate
  dataset$B1_2 <- df2$Price
  dataset$B1_3 <- df3$Code

The error that I get:

Error in `$<-.data.frame`(`*tmp*`, B1_1, value = c(5L, 7L, 9L, 11L, 13L,  : 
  replacement has 10 rows, data has 0 

I checked that each of df1$Rate, df2$Price, and df3$Code has data, in other words, they are not empty. Also, I also checked the data type of these columns and all of the three columns of integer type.

How can I solve it?

Adam Amin
  • 1,406
  • 2
  • 11
  • 23
  • This question already has an answer here: https://stackoverflow.com/questions/26684072/add-columns-to-an-empty-data-frame-in-r Hope this helps you – jessi Feb 15 '19 at 19:43

1 Answers1

1

Here's a way to replace a column of a zero-row data frame with a positive number of values.

# an example data frame with 2 columns and 0 rows
dat <- data.frame(a = integer(), b = integer())

# a vector of values that should be added to column "a"
vec <- 1:3

# create a data frame with the correct number of rows and add the values to the column
dat[seq_along(vec), ]$a <- vec

#      a  b
# NA   1 NA
# NA.1 2 NA
# NA.2 3 NA
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168