Jeff
Jeff

Reputation: 8421

How to convert String of array to Integer array

I have a string as "2_5_6". i need to get the numbers in the string As numeric.

Here is what i tried:

indices = apply(strsplit("2_5_6","_" ),2 ,FUN = as.numeric) 

But, it complains with:

Error in apply(strsplit("2_5_6", "_"), 2, FUN = as.numeric) : 
  dim(X) must have a positive length

I don't know what should be my Margin parameter ?

What is the simplest solution for it?

Upvotes: 2

Views: 53

Answers (3)

s_baldur
s_baldur

Reputation: 33488

as.numeric(strsplit("2_5_6","_" )[[1]])

Upvotes: 0

Liuk
Liuk

Reputation: 361

Best practice is to use a Comma Separated Files ( .csv ) file.

Use this file to set and get params useful to configure your algorithm/procedure.

Save the file with .csv extension and read it using the function read.csv(...).

In your case, use:

myMargin <- read.csv(file="mymargin.csv", header=FALSE, sep="_")

If you need more information, this is the documentation:

https://stat.ethz.ch/R-manual/R-devel/library/utils/html/read.table.html

Upvotes: 0

akrun
akrun

Reputation: 887213

We can use scan to convert to numeric while splitting at _

scan(text = "2_5_6", what = numeric(), sep="_", quiet = TRUE)
#[1] 2 5 6

Or if we are using strsplit, the output is a list of length 1. It can be either unlisted or extracted ([[)

as.integer(unlist(strsplit("2_5_6", "_")))

apply expects the input to have some dimensions and here it doesn't have

Upvotes: 1

Related Questions