How to unlist and paste without the column ID

Hi
I am new in r. Just one year learner.
I have created a list of patient id's with their diagnosis. I want to transform the resulted list to just a list of diagnosis for each patient separated by a comma, without the patient_sk. This is my code; I just think that I should use unlist and paste. Any ideas?

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

Ok, Thank you I will try.
It was so difficult to produce this code already. I will try to find a similar reproducible dataset.

To demonstrate your problem, it probably doesn't need to be real dataset, often you can just make up some fake data that fits the pattern in your real data. From your description of the data, it sounds like you might have something like this:


data <- replicate(6, sample(letters, 3), simplify = FALSE)
names(data) <- paste0("id_", 1:6)

data
#> $id_1
#> [1] "r" "j" "z"
#> 
#> $id_2
#> [1] "r" "n" "w"
#> 
#> $id_3
#> [1] "k" "x" "z"
#> 
#> $id_4
#> [1] "j" "c" "b"
#> 
#> $id_5
#> [1] "b" "y" "v"
#> 
#> $id_6
#> [1] "d" "w" "m"

I'm not clear on your expected output but if you want to collapse each vector of diagnoses into a single comma separate character, you can do this:

lapply(data, paste, collapse = ", ")
#> $id_1
#> [1] "r, j, z"
#> 
#> $id_2
#> [1] "r, n, w"
#> 
#> $id_3
#> [1] "k, x, z"
#> 
#> $id_4
#> [1] "j, c, b"
#> 
#> $id_5
#> [1] "b, y, v"
#> 
#> $id_6
#> [1] "d, w, m"

Created on 2020-01-29 by the reprex package (v0.3.0)

1 Like

I want it without the $id_1 to appear, only [1] "r, j,z" and so on...

#> [1] "r, j, z"
#> [1] "r, n, w"
#> [1] "k, x, z"
#> [1] "j, c, b"
#> [1] "b, y, v"
#> [1] "d, w, m"

What type of object do you want to return? If it's just an unnamed list, you can do this:

data <- replicate(6, sample(letters, 3), simplify = FALSE)
names(data) <- paste0("id_", 1:6)

new_data <- lapply(data, paste, collapse = ", ")
names(new_data) <- NULL

new_data
#> [[1]]
#> [1] "m, a, h"
#> 
#> [[2]]
#> [1] "j, f, g"
#> 
#> [[3]]
#> [1] "v, x, b"
#> 
#> [[4]]
#> [1] "m, z, v"
#> 
#> [[5]]
#> [1] "y, f, d"
#> 
#> [[6]]
#> [1] "b, d, s"

Created on 2020-01-29 by the reprex package (v0.3.0)

1 Like

Yes! that works, thank you. I wanted an unnamed list exactly. I just did not know the terminology.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.