Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to split a specific column based on symbol in R? [duplicate]

Tags:

split

r

Possible Duplicate:
Replacing ^ and | sybmbols in a matrix

In previous message (Replacing ^ and | sybmbols in a matrix), the way to remove a symbol in a list wass discussed.

Here I want to replace only one column (column Drug) of a matrix. For example:

Patient Hospital Drug Response
111     AAA      B+A  Good
222     CCC      B    Good
333     DDD      A+C  Bad+relapse

To the following formats.

Patient Hospital Drug1 Drug2 Response
111     AAA      B     A     Good
222     CCC      B     NA    Good
333     DDD      A     C     Bad+relapse

What is the way to do so with R.

like image 714
Catherine Avatar asked Apr 10 '11 05:04

Catherine


People also ask

How do I split a column by a character in R?

To split a column into multiple columns in the R Language, we use the separator() function of the dplyr package library. The separate() function separates a character column into multiple columns with a regular expression or numeric locations.

How do I separate specific data in R?

Use the split() function in R to split a vector or data frame. Use the unsplit() method to retrieve the split vector or data frame.

How do I split a column by delimiter in Excel?

Select Home > Split Column > By Delimiter. The Split a column by delimiter dialog box appears. In the Select or enter a delimiter drop-down, select Colon, Comma, Equals Sign, Semicolon, Space, Tab, or Custom. You can also select Custom to specify any character delimiter.


1 Answers

Like this:

df <- data.frame(drug1 = c("B+A", "B", "A+C"))
df
df$drug2 <- lapply(strsplit(as.character(df$drug1), "\\+"), "[", 2)
df$drug1 <- lapply(strsplit(as.character(df$drug1), "\\+"), "[", 1)
df

resulting

> df
  drug1 drug2
1     B     A
2     B    NA
3     A     C
> 
like image 72
jrara Avatar answered Sep 22 '22 16:09

jrara