Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a number as single characters in r

Tags:

r

I have an input file which looks like

222222222224444444444444444477777777777723548464646
233333333224444444444444444477776666667723545864646

When I read it into r with the Read table command R thinks it is a single number in 1 column. However, I would need to have a column for each single character

2 2 2 2 2   2

...

Is there a way to do this in** **R?

like image 424
user3419669 Avatar asked Dec 09 '25 03:12

user3419669


2 Answers

You can treat it as a fixed width file, and open with read.fwf, giving the width argument a vector of 1s the same length as the (maximum) number of characters per line:

read.fwf("yourFilename", rep(1, chars))

where yourFilename is the name of your file, and chars is the number of characters per line (51 in your example).

If any rows have less characters than the chars value you set, they will be given the value NA

like image 58
ping Avatar answered Dec 10 '25 18:12

ping


First, it might be easiest to read in the data with readLines. Then you can use strsplit to easily separate each string (sequence of numbers) into single digits.

Here's an example (I first write out the dummy data to a temporary file, f):

cat('222222222224444444444444444477777777777723548464646
233333333224444444444444444477776666667723545864646', file=f <- tempfile())
d <- readLines(f)
apply(do.call(rbind, strsplit(d, '')), 2, as.numeric)

The last line of code is firstly splitting each line of your text file into single characters, then binding each separated string into a data.frame (with do.call(rbind, ...)). Finally, we coerce it to numeric. You could leave it as do.call(rbind, strsplit(d, '')) if you're happy to leave the object as character data.

See ?strplit for more info.

like image 36
jbaums Avatar answered Dec 10 '25 17:12

jbaums



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!