Paul85 - 2 months ago 8x

R Question

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`

`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`

Answer

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.

Source (Stackoverflow)

Comments