Parker McColl
Parker McColl

Reputation: 23

Trim text after character for every item in list - R

I am trying to remove the text before and including a character ("-") for every element in a list.

Ex-

x = list(c("a-b","b-c","c-d"),c("a-b","e-f"))

desired output:

"b" "c" "d"     
"b" "f"

I have tried using various combinations of lapply and gsub, such as

lapply(x,gsub,'.*-','',x)

but this just returns a null list-

[[1]]
[1] ""

[[2]]
[1] ""

And only using

gsub(".*-","",x)

returns

"d\")" "f\")"

Upvotes: 2

Views: 548

Answers (2)

Brian
Brian

Reputation: 8275

You are close, but using lapply with gsub, R doesn't know which arguments are which. You just need to label the arguments explicitly.

x <- list(c("a-b","b-c","c-d"),c("a-b","e-f"))
lapply(x, gsub, pattern = "^.*-", replacement = "")
[[1]]
[1] "b" "c" "d"

[[2]]
[1] "b" "f"

Upvotes: 2

Nirad
Nirad

Reputation: 41

This can be done with a for loop.

val<-list()
for(i in 1:length(x)){
  val[[i]]<-gsub('.*-',"",x[[i]])}
val
[[1]]
[1] "b" "c" "d"

[[2]]
[1] "b" "f"

Upvotes: 2

Related Questions