CHRD
CHRD

Reputation: 1957

Manipulate list of character lists in R

I have a list of unnamed, comma separated character lists:

> list
[[1]]
[1] "A" "B" "C" "D"

[[2]]
[1] "E" "F" "G"

The actual list is long, and each character list inside it is of random length and contains different, unpredictable, character combinations. I need to apply three things to each element of all of the character lists:

I am new to R and guess this is a trivial task. I'd be very happy if someone was willing to help me out! Cheers :)

Upvotes: 3

Views: 905

Answers (1)

Joris Meys
Joris Meys

Reputation: 108523

To do any operation on a list, you can use the apply family to loop over it. Using lapply you get a list back, which is what you want. lapply takes the list as a first argument, and then any kind of function you want really.

So let's start from:

mylist <- list(
  LETTERS[1:4],
  LETTERS[5:7],
  c("A/BCD","H","J")
)

Removing "A" in every element of the list goes like this:

lapply(mylist, function(x) x[x!="A"])

Replacing elements would go like this:

lapply(mylist, function(x) {
  id <- x == "B"
  x[id] <- "F"
  return(x)
})

Editing the values in each element can be done using gsub like this:

lapply(mylist, function(x){
  gsub("/.+","",x)
})

You can combine everything in one function, and then apply that function to the list. You don't have to create that as an anonymous function inside the lapply call, you can predefine it and then use it like this:

cleanup <- function(x){
  x <- gsub("/.+","",x) # remove extra info
  id <- x %in% c("A","H")
  x[id] <- "F"
  return(x)
}

lapply(mylist, cleanup)

The principle is always the same: each time I create an anonymous function that takes a vector as input and returns the adapted vector as output. lapply will make sure these different elements are combined back into a list.

Upvotes: 2

Related Questions