Paul85
Paul85

Reputation: 657

r-concatenate for n elements from list

I am trying to read data from a column and then concatenate my desired information into a string.

So far I wrote R script successful for a single string input, but I can't mange to do it for n elements.

reprows <- strsplit("Day1_XExp2B3_500x_Y_Z", "_", fixed = T)
lenreprows <- length(reprows[[1]])
temprepnamelisttopaste <- c(2:(lenreprows-2))
temprepname <- paste(sapply(reprows[temprepnamelisttopaste]),collapse='.')

Data looks like in each row:

Day1_XExp2B3_500x_Y_Z

My output should be:

XExp2B3.500x

Upvotes: 0

Views: 266

Answers (2)

alistaire
alistaire

Reputation: 43334

strsplit produces a list when you pass it a vector, so you need an *apply function to manipulate each result. Regex may be a more straightforward option, depending on what you know about the strings:

x <- c("Day1_XExp2B3_500x_Y_Z", "Day1_XExp2B3_500x_Y_Z")

sub("\\w+_(\\w+)_(\\w+)_._.", "\\1.\\2", x)
## [1] "XExp2B3.500x" "XExp2B3.500x"

Upvotes: 1

Zheyuan Li
Zheyuan Li

Reputation: 73285

How about

## a function for re-concatenation
rc <- function (u) paste0(u[2:(length(u)-2L)], collapse = ".")
## main code
unlist(lapply(strsplit(x, "_", fixed = T), rc))

where x is your character column with many elements. I made a simple test with

x <- rep("Day1_XExp2B3_500x_Y_Z", 2)

and the codes gives

#[1] "XExp2B3.500x" "XExp2B3.500x"

Looks like working fine.

Upvotes: 2

Related Questions