Spliting a row into columns using a delimiter in R

45 views Asked by At

My data loks like this:

ID:10:237,204,
ID:11:257,239,
ID:12:309,291,
ID:13:310,272,
ID:14:3202,3184,
ID:15:404,388,

I would like to first separate this into different columns then apply a function on each row to calculate the difference of comma separated values such as (237-204). Without the use of external library packages.

1

There are 1 answers

0
G. Grothendieck On

Try this except if the data is in a file replace the readLines line with something like this: L <- readLines("myfile.csv") . After that replace the colons with commas using gsub and then read the resulting text and transform it:

# test data
Lines <- "ID:10:237,204,
ID:11:257,239,
ID:12:309,291,
ID:13:310,272,
ID:14:3202,3184,
ID:15:404,388,"

L <- readLines(textConnection(Lines))
DF <- read.table(text = gsub(":", ",", L), sep = ",")
transform(DF, diff = V3 - V4)

giving:

  V1 V2   V3   V4 V5 diff
1 ID 10  237  204 NA   33
2 ID 11  257  239 NA   18
3 ID 12  309  291 NA   18
4 ID 13  310  272 NA   38
5 ID 14 3202 3184 NA   18
6 ID 15  404  388 NA   16