【问题标题】:Row binding a data frame with an embedded data frame in R?将数据框与R中的嵌入式数据框绑定的行?
【发布时间】:2020-08-20 02:30:11
【问题描述】:

我正在尝试将数据与另一行进行 rbind。但我不断收到以下错误:

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’ 

我几乎可以肯定这与我的数据框在数据框有一个数据框这一事实有关。

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

我的问题是,如果数据帧中嵌入了数据帧,我如何将数据与另一行或另一个类似维度的数据集进行绑定。或者如何将数据帧与嵌入的数据帧分开?

这就是我想要开始的工作:

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

请注意,这是数据集的截断子集,其中包括数字和字符串变量,因此使用 as.numeric 对我不起作用,因为它是字符串值变量NA

这是数据:

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")))

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    试试这个。

    > 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
    

    【讨论】:

      【解决方案2】:

      您可以使用do.call 生成正确的data.frame

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-13
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-09
        • 2019-03-09
        • 2017-07-05
        相关资源
        最近更新 更多