Unlist a list of multiple elements in R

Viewed 382

I have extracted data from twitter and it appears as the column List (what you will get after running the code). I want the output as what appears in the Broken column.

Image for data

data <- data.frame(matrix(, nrow=4, ncol=2))
colnames(data)[1:2] <- c("List", "Broken")
data$List[1] <- 1
data$List[2] <- list(c("1", "SmythsToysUK"))
data$List[3] <- list(c("1", "FortniteGame", "CityCtrMirdif", "itpliveme"))
data$List[4] <- 1
data$Broken[1:4]<- c("SmythsToysUK","FortniteGame","CityCtrMirdif","itpliveme")
2 Answers

We can remove all the numbers from List column.

temp <- unlist(data$List)
data$Broken <- temp[is.na(as.numeric(temp))]
data

#                                       List        Broken
#1                                         1  SmythsToysUK
#2                           1, SmythsToysUK  FortniteGame
#3 1, FortniteGame, CityCtrMirdif, itpliveme CityCtrMirdif
#4                                         1     itpliveme

We can use grep with unlist. After unlisting the list, select only the elements that have letters

data$Broken <- grep("[A-Za-z]", unlist(data$List), value = TRUE)
data$Broken
#[1] "SmythsToysUK"  "FortniteGame"  "CityCtrMirdif" "itpliveme"   

Or another option is to remove the first element which seems to be index and then unlist

unlist(sapply(data$List, `[`, -1))

NOTE: Both the options, doesn't have any warnings

Related