I have a dataframe df
where one of the columns user
is itself a 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?
The data.frame
structure showed in the OP's post is not reproducible. So, constructed a 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. Instead use a list
df <- tibble(user = tibble(id = 1, name = "joe"), color = "green")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.