Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace specific column "words" into number or blank

Tags:

replace

numbers

r

Input table

Patients  Hospital   Drug   Response
1         AAA        a      Good
1         AAA        a      Bad
2         BBB        a      Bad
3         CCC        b      Good
4         CCC        c      Bad
5         DDD        e      undefined 

Output file

Patients  Hospital   Drug   Response
1         AAA        a      1
1         AAA        a      -1
2         BBB        a      -1
3         CCC        b      1
4         CCC        c      -1
5         DDD        e       

How to replace 3 texts in one column to number and blank?

"good in Reponse column" to "1" "bad in Reponse column" to "-1" "undefined in Reponse column" to " "

Data:

structure(list(Patients = c(1L, 1L, 2L, 3L, 4L, 5L), Hospital = structure(c(1L, 
1L, 2L, 3L, 3L, 4L), .Label = c("AAA", "BBB", "CCC", "DDD"), class = "factor"), 
    Drug = structure(c(1L, 1L, 1L, 2L, 3L, 4L), .Label = c("a", 
    "b", "c", "e"), class = "factor"), Response = structure(c(2L, 
    1L, 1L, 2L, 1L, 3L), .Label = c("Bad", "Good", "undefined"
    ), class = "factor")), .Names = c("Patients", "Hospital", 
"Drug", "Response"), class = "data.frame", row.names = c(NA, 
-6L))
like image 693
Catherine Avatar asked Apr 10 '11 15:04

Catherine


3 Answers

You can do this with one line by changing the labels of the factor Response:

> within(df, Response <- factor(Response, labels = c(-1, 1, "")))
  Patients Hospital Drug Response
1        1      AAA    a        1
2        1      AAA    a       -1
3        2      BBB    a       -1
4        3      CCC    b        1
5        4      CCC    c       -1
6        5      DDD    e         
like image 169
Gavin Simpson Avatar answered Nov 03 '22 13:11

Gavin Simpson


Catherine, your questions could still be answered by a very basic textbook in R. Please see Dirk's comment in your previous question.

Answer

If d is your data frame, then:

d[d$Response == "Good",]$Response = 1
d[d$Response == "Bad",]$Response = -1
d[d$Response == "undefined",]$Response = ""

I'm guessing (I may be wrong) that "Undefined" is missing data. In which case, use NA rather than a blank. Any basic R book will describe NA's

like image 5
csgillespie Avatar answered Nov 03 '22 14:11

csgillespie


If your data is in a data frame df

df$Response[df$Response == "Good"] <- 1
df$Response[df$Response == "Bad"] <- -1
df$Response[df$Response == "undefined"] <- ""
like image 3
Noah Avatar answered Nov 03 '22 12:11

Noah