JNab
JNab

Reputation: 135

How to paste all string values in a column together as one?

I have a dataframe consisting of 2 columns called Q1Dummy: respondent ID and responses they made in a string format.

It looks like this:

resp_id    Q1
1          Ik vind het niet helemaal netjes om je sociale huurwoning te verhuren, aangezien je dan mensen passeert die al lang op de wachtrij staan of er meer recht op hebben.
2          Ja dat vind ik heel goed omdat mensen die al heel lang op zoek zijn ook een huisje kunnen krijgen.
3          Ik vind het iets begrijpelijks. Als je in de sociale huur zit, geeft het al aan dat je een klein inkomen hebt. Het is fijn om de woning dan achter de hand te hebben als extra inkomen en uitvalsbasis in een stad als Amsterdam. Ook de huur illegaal met iemand delen, waardoor je beide geld bespaard, is een logisch gevolg van de krapte op de huizenmarkt. Ondanks dat het iets illegaals is kan ik er dus begrip voor opbrengen.
...        ...
n          Dat kan echt niet. Je maakt winst op een woning waar subsidie opzit. Daar is de woning niet voor bedoeld.

Now, for text mining purposes I would like to unnest the responses in ngrams (of 3), as I tried below:

tokensQ1Dummy <- Q1Dummy %>%
    unnest_tokens(words, Q1, token = "ngrams", n = 3, n_min = 1) %>%
    count(resp_id, words, sort = TRUE)

However, when I try this the created 'words' column consists of multiple issues of the same word. So in this case it would show the word 'de' multiple times, for the multiple users:

 resp_id  words     count
 3        de        6
 3        het       4
 5        de        4

But what I want is to consider all responses as 'one' response, so that the important subjects returning in multiple responses will be considered as one subject, and thus that the word 'de' will only come up once (since it is the same word, but used by multiple respondents). How do I go about this?

Upvotes: 1

Views: 1025

Answers (1)

DeduciveR
DeduciveR

Reputation: 1702

You need to group by resp_id, summarise and collapse to concatenate into one. Difficult to illustrate precisely from your data example but the code is something like:

library(tidyverse)

df %>%
  group_by(resp_id) %>%
  summarise(col = paste(Q1, collapse=" "))

Upvotes: 2

Related Questions