Gigi39
Gigi39

Reputation: 45

Rename elements of a list

I am creating a large list pulling variables from a dataframe. Here is an example:

df <- data.frame (A-Imp = c(4,8,2,4,3),
      A-Rea = c(4,4,5,6,7),
      B-Imp = c(3,2,6,5,8),
      B-Rea = c(1,2,6,7,9),
      C-Imp = c(4,8,6,6,10),
      C-Rea = c(6,8,5,1,9),
      D-Imp = c(1,6,4,8,8),
      D-Rea = c(3,3,6,1,10))

groups <- list(
   "groupA" <- c("A-Imp", "A-Rea"),
   "groupB" <- c("B-Imp", "B-Rea"),
   "groupC" <- c("C-Imp", "C-Rea"),
   "groupD" <- c("D-Imp", "D-Rea"))

What I want to do is to rename the entries of every vector, maintaining only the last part of the name. It would look like something like this:

groups <- list(
   "groupA" <- c("Imp", "Rea"),
   "groupB" <- c("Imp", "Rea"),
   "groupC" <- c("Imp", "Rea"),
   "groupD" <- c("Imp", "Rea"))

Since it is a very long list I don't want to do it manually. Any ideas on how I can proceed?

Upvotes: 1

Views: 328

Answers (4)

akrun
akrun

Reputation: 887108

Using map and str_remove

library(purrr)
library(stringr)
map(groups, str_remove, pattern = ".*-")

-output

#[[1]]
#[1] "Imp" "Rea"

#[[2]]
#[1] "Imp" "Rea"

#[[3]]
#[1] "Imp" "Rea"

#[[4]]
#[1] "Imp" "Rea"

Upvotes: 0

hello_friend
hello_friend

Reputation: 5788

Using Map():

Map(function(x){gsub("^\\w\\-", "", x)}, groups)

Upvotes: 1

s_baldur
s_baldur

Reputation: 33488

groups <- lapply(groups, sub, pattern = "[A-Z]-", replacement = "")

str(groups)
List of 4
 $ : chr [1:2] "Imp" "Rea"
 $ : chr [1:2] "Imp" "Rea"
 $ : chr [1:2] "Imp" "Rea"
 $ : chr [1:2] "Imp" "Rea"

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

Using sub you can remove everything until underscore.

result <- lapply(groups, function(x) sub('.*-', '', x))
result

#[[1]]
#[1] "Imp" "Rea"

#[[2]]
#[1] "Imp" "Rea"

#[[3]]
#[1] "Imp" "Rea"

#[[4]]
#[1] "Imp" "Rea"

Upvotes: 1

Related Questions