Home > Net >  Using a list of characters in a function? [duplicate]
Using a list of characters in a function? [duplicate]

Time:10-02

I am using a function where Timepoints need to be defined as
Timepoints = c(x,y,z)

Now i have a chr list

List 

  $ chr: "1,2,3,4,5,6,7" 

with the timepoints i need to use, already seperated by commas. I want to use this list in the function and lose the quotation marks, so the function can read my timepoints as

Timepoints= c(1,2,3,4,5,6,7)

I tried using noquote(List), but this is not accepted.

Am is missing something ? printing the list with noquote() results in the desired line of characters 1,2,3,4,5,6,7

CodePudding user response:

1) Base R - scan Assuming that you have a list containing a single character string as shown in L below use scan as shown.

L <- list("1,2,3,4,5,6")
scan(text = L[[1]], sep = ",", quiet = TRUE)
## [1] 1 2 3 4 5 6

2) gsubfn::strapply Another possibility is to use strapply to match each string of digits, convert them to numeric and return it as a vector.

library(gsubfn)

strapply(L[[1]], "\\d ", as.numeric, simplify = unlist)
[1] 1 2 3 4 5 6

Added

In a comment the poster indicated an interest in having a list of character strings as input. The output was not specified but if we assume we want a list of numeric vectors then

L2 <- list(A = "1,2,3,4,5,6", B = "1,2")

Scan <- function(x) scan(text = x, sep = ",", quiet = TRUE)
lapply(L2, Scan)
## $A
## [1] 1 2 3 4 5 6
## 
## $B
## [1] 1 2

library(gsubfn)
strapply(L2, "\\d", as.numeric)
## $A
## [1] 1 2 3 4 5 6
##
## $B
## [1] 1 2

CodePudding user response:

Here is an option with strsplit.

as.integer(unlist(strsplit(L[[1]], ",")))
#[1] 1 2 3 4 5 6
  •  Tags:  
  • r
  • Related