[英]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
列拆分为id
和name
列,以便df
具有id
和name
列而不是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
df <- tibble(user = tibble(id = 1, name = "joe"), color = "green")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.