Ankit Solanki
Ankit Solanki

Reputation: 680

R: Extracting Numbers from a string separated by comma

I have a data frame for example,

X1 12:37  
X2  3,0,0

I want to extract 3 0 and 0 individually into a new data frame.

Ne idea how could I do it??

Thanks in advance...

Upvotes: 2

Views: 3013

Answers (3)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

Using @agstudy's "res1":

res1 <- read.table(
  text='X1 12:37
  X2  3,0,0')
temp <- read.table(text = as.character(res1$V2), 
                   sep = ",", header = FALSE, fill = TRUE)
temp
#      V1 V2 V3
# 1 12:37 NA NA
# 2     3  0  0
temp[complete.cases(temp), ]
#   V1 V2 V3
# 2  3  0  0

Upvotes: 1

agstudy
agstudy

Reputation: 121568

You can start by reading your Lines ans splitting them to extract Number from row names.

ll <- readLines(textConnection('X1 12:37  
X2  3,0,0'))
res <- strsplit(ll,' ')
[[1]]
[1] "X1"    "12:37" ""     

[[2]]
[1] "X2"    ""      "3,0,0"

Or using read.table:

res1 <- read.table(text='X1 12:37  
X2  3,0,0')
  V1    V2
1 X1 12:37
2 X2 3,0,0

Than you can access the elements containing comma for example, and apply strsplit again as mentioned by the other solution.

unlist(res)[grep(',',unlist(res))]
 "3,0,0"

Upvotes: 3

Hong Ooi
Hong Ooi

Reputation: 57686

You can get the numbers out using strsplit:

strsplit("3,0,0", ",")

It's not entirely clear if your data is actually in a data frame, or just a vector (people new to R have a tendency to call everything containing data as a "data frame"), but hopefully you can see how to apply the function.

Upvotes: 1

Related Questions