Reputation: 1
I am new to R. I have a data frame like this:
Category description
Analysis This is one
Hybrid This is two
Other This is three
Analysis This is four
Other This is five
Hybrid This is six
And I would Like to get description per category in a list form like this:
Category description
Analysis ("This is one", "This is four")
Hybrid ("This is two", "This is six")
Other ("This is five", "This is three")
Upvotes: 0
Views: 24
Reputation: 4344
If you want the data to be in nested lists inside the original data.frame/tibble this would be an option:
library(dplyr)
library(tidyr)
library(data.trable)
# reading in your dummy data
df <- data.table::fread("Category description
Analysis 'This is one'
Hybrid 'This is two'
Other 'This is three'
Analysis 'This is four'
Other 'This is five'
Hybrid 'This is six'")
res <- df %>%
# helper line to prepare de read in data
tidyr::unite("description", description:V4, sep = " ") %>%
# build a grouping you need
dplyr::group_by(Category) %>%
# nest the wanted column to a list
tidyr::nest(description)
res
# A tibble: 3 x 2
# Groups: Category [3]
Category data
<chr> <list>
1 Analysis <tibble [2 x 1]>
2 Hybrid <tibble [2 x 1]>
3 Other <tibble [2 x 1]>
res[2][[1]]
[[1]]
# A tibble: 2 x 1
description
<chr>
1 'This is one'
2 'This is four'
[[2]]
# A tibble: 2 x 1
description
<chr>
1 'This is two'
2 'This is six'
[[3]]
# A tibble: 2 x 1
description
<chr>
1 'This is three'
2 'This is five'
Upvotes: 0
Reputation: 11584
Does this work:
library(dplyr)
df %>% group_by(Category) %>%
mutate(description = str_c('"',description, '"')) %>%
summarise(description = str_c('(',toString(description),')'))
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 2
Category description
<chr> <chr>
1 Analysis "(\"This is one\", \"This is four\")"
2 Hybrid "(\"This is two\", \"This is six\")"
3 Other "(\"This is three\", \"This is five\")"
cat(x$description)
("This is one", "This is four") ("This is two", "This is six") ("This is three", "This is five")
Data used:
dput(df)
structure(list(Category = c("Analysis", "Hybrid", "Other", "Analysis",
"Other", "Hybrid"), description = c("This is one", "This is two",
"This is three", "This is four", "This is five", "This is six"
)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,
-6L), spec = structure(list(cols = list(Category = structure(list(), class = c("collector_character",
"collector")), description = structure(list(), class = c("collector_character",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1L), class = "col_spec"))
Upvotes: 1