简体   繁体   English

如何在保留其他列类型的同时拆分“data.frame”类型列?

[英]How do I split a “data.frame” type column while preserving other column types?

I have a dataframe df where one of the columns user is itself a data.frame .我有一个 dataframe df其中一个列user本身就是一个data.frame

df <- data.frame(
  user = data.frame(
    id = numeric(),
    name = character()
  ),
  color = character()
)

df[nrow(df)+1,] <- c(1,"joe","green")

How do I split the user column into the id and name columns so that df has the id and name columns instead of the user column, while keeping the color column?如何将user列拆分为idname列,以便df具有idname列而不是user列,同时保留color列?

The data.frame structure showed in the OP's post is not reproducible. OP 帖子中显示的data.frame结构不可重现。 So, constructed a tibble所以,构建了一个tibble

library(tibble)
library(tidyr)
library(dplyr)
df1 <- df %>%
            mutate(user = list(user)) %>%
            unnest_wider(c(user)) 

str(df1)
#tibble [1 × 3] (S3: tbl_df/tbl/data.frame)
# $ id   : num 1
# $ name : chr "joe"
# $ color: chr "green"

NOTE: when we adding a new row with assignment, if we choose a vector ( c(...) ), there is a limitation in having different types as vector allows only a single type.注意:当我们添加一个带赋值的新行时,如果我们选择一个向量( c(...) ),那么具有不同类型的限制是有限的,因为vector只允许单一类型。 Instead use a list而是使用list

data数据

df <- tibble(user = tibble(id = 1, name = "joe"), color = "green")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM