jessica
jessica

Reputation: 1355

Row binding a data frame with an embedded data frame in R?

I am trying to rbind data with another additional row. But I keep getting the following error:

Error in `.rowNamesDF<-`(x, value = value) : 
  duplicate 'row.names' are not allowed
In addition: Warning message:
non-unique values when setting 'row.names': ‘1’, ‘2’, ‘3’, ‘4’ 

I am nearly certain it has to do with the fact that my data frame has a data frame within the data frame.

class(data)
[1] "dfidx_mlogit" "dfidx"        "data.frame"   "mlogit.data" 

My question is how do I rbind the data with another row or another data set of similar dimension if the dataframe has a dataframe embedded in it. OR How do I seperate the dataframe from the embedded dataframe?

This is what I am trying to get to work:

#Row bind the dataset with itself.
new_data=rbind(data,data)

Note that this is a truncated subset of the dataset, which includes numeric and string variables, so using as.numeric does not work for me because it string valued variables NA

Here is the data:

data=structure(list(EDUC = c(4L, 4L, 4L, 4L), HEALTH = c(3L, 3L, 3L, 
3L), idx = structure(list(chid = c(1L, 1L, 1L, 1L), unique_id = c(3000175513, 
3000175513, 3000175513, 3000175513), alt = structure(1:4, .Label = c("Bicycle", 
"Car", "Metro", "Walking"), class = "factor")), ids = c(1, 1, 
2), row.names = c(NA, 4L), class = c("idx", "data.frame"))), row.names = c(NA, 
4L), class = c("dfidx_mlogit", "dfidx", "data.frame", "mlogit.data"
), idx = structure(list(chid = c(1L, 1L, 1L, 1L), unique_id = c(3000175513, 
3000175513, 3000175513, 3000175513), alt = structure(1:4, .Label = c("Bicycle", 
"Car", "Metro", "Walking"), class = "factor")), ids = c(1, 1, 
2), row.names = c(NA, 4L), class = c("idx", "data.frame")))

Upvotes: 0

Views: 109

Answers (2)

jay.sf
jay.sf

Reputation: 72803

You may generate a proper data.frame using do.call.

res <- do.call(data.frame, data) 
str(res)
# 'data.frame': 4 obs. of  5 variables:
# $ EDUC         : int  4 4 4 4
# $ HEALTH       : int  3 3 3 3
# $ idx.chid     : int  1 1 1 1
# $ idx.unique_id: num  3e+09 3e+09 3e+09 3e+09
# $ idx.alt      : Factor w/ 4 levels "Bicycle","Car",..: 1 2 3 4

Upvotes: 1

Haci Duru
Haci Duru

Reputation: 456

Try this.

> row.names(data$idx) <- c()
> row.names(data) <- c()
> 
> data_new <- rbind(data, data)
> data_new
  EDUC HEALTH idx.chid idx.unique_id idx.alt
1    4      3        1    3000175513 Bicycle
2    4      3        1    3000175513     Car
3    4      3        1    3000175513   Metro
4    4      3        1    3000175513 Walking
5    4      3        1    3000175513 Bicycle
6    4      3        1    3000175513     Car
7    4      3        1    3000175513   Metro
8    4      3        1    3000175513 Walking

Upvotes: 1

Related Questions