a function that accepts a string

I have a function that takes a string as an argument. z <- p.str('0.002 0.003 0.555')

p.str <- function(mystr){
  
  p.ad <-  p.adjust(as.numeric(strsplit(mystr, " "))) #
  mystr<- as.numeric(strsplit(mystr, " ")) #
  rez <- paste(mystr,p.ad,collapse='\n') #
  
  return(rez)
}

z <- data.table(z)

p.ad - calculates adjusted values

mystr - string as we write it and translate it numeric

then I write to data.table.

I get an error: 'list' object cannot be coerced to type 'double'

what I expect:

|     z        |
|--------------|
|  0.002 0.006 |
|  0.003 0.006 |
|  0.555 0.555 | 

Upvotes: 0

Views: 42

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 145765

strsplit returns a list. This is because it is vectorized, e.g., strsplit(c("1 2", "3 4 5"), split = " ").

If you know the input character string will be of length 1, then you can safely use unlist(strsplit(...)) or strsplit(...)[[1]]. You could also check that the input is of length 1.

Also, it's inefficient and bad practice to have as.numeric(strsplit(mystr, " ")) repeated in your function. If you need to use that result more than once, assign it to an object.

p.str <- function(mystr){
  
  num  <- as.numeric(unlist(strsplit(mystr, " ")))
  p.ad <- p.adjust(num) 
  paste(num, p.ad, collapse='\n')

}

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 388862

Try this function :

p.str <- function(mystr){
  vec <- as.numeric(strsplit(mystr, " ")[[1]])
  p.ad <-  p.adjust(vec) #
  rez <- paste(vec,p.ad,collapse='\n') 
  return(rez)
}

cat(p.str('0.002 0.003 0.555'))

#0.002 0.006
#0.003 0.006
#0.555 0.555

Upvotes: 1

Related Questions