djc1223
djc1223

Reputation: 55

undo str_split to combine words is a paragraph? (R)

I currently have a list of 27 paragraphs called psw_list and can refer to the first one by calling psw_list$p1, and it looks like this:

> psw_list$p1

 [1] "For"          "more"         "than"         "five"         "years,"       "William"      "Sencion"     
 [8] "did"          "the"          "same"         "task"         "over"         "and"          "over."       
[15] "He"           "signed"       "onto"         "the"          "New"          "York"         "City’s"      
[22] "housing"      "lottery"      "site"         "and"          "applied"      "for"          "one"         
[29] "of"           "the"          "city’s"       "highly"       "coveted,"     "below-market" "apartments." 
[36] "Each"         "time,"        "he"           "got"          "the"          "same"         "response:"   
[43] "silence."  

I want to remove the spaces between each word and this line does so to individual lines, paste(psw_list$p1,collapse=" "), but does not work in a for loop:

for (i in seq_along(psw_list)) {
  print(paste(psw_list$[i], collapse = " "))
}

I'm getting an unexpected '[' error when I run this loop. I want the for loop because I want it to go through each paragraph and collapse the words together separated by that one space, any ideas?

Upvotes: 0

Views: 56

Answers (2)

ljwharbers
ljwharbers

Reputation: 393

Your error is due to psw_list$[i] if you replace this with psw_list[[i]] which selects the column i it will run without a problem.

Another solution to this would be to use the apply() family. For instance running the following:

lapply(psw_list, function(i) paste(i, collapse = " "))

Upvotes: 1

Georgery
Georgery

Reputation: 8117

Here is a solution without the for-loop:

lapply(psw_list, paste, collapse = " ")

or if you really want the for-loop:

for (i in seq_along(psw_list)) {
  print(paste(psw_list[[i]], collapse = " "))
}

Upvotes: 1

Related Questions