2017-07-24 1 views
-3

J'ai un ensemble de données comme:Retirer cellule spécifique d'un jeu de données en r

A    B        C 
    hello   Radiation therapy    NA 
    Hello1   hello2 for neurology   hello3 radiation 

et beaucoup plus de lignes.

Maintenant, j'ai l'intention d'enlever tout le texte après "pour" comme pour "neurologie" et aussi tout le texte contenant "radiation". Donc, je me attends à la sortie soit:

A    B       C 
    hello   therapy      NA 
    Hello1   hello2      hello3 

Répondre

0

Exemple dataframe:

df <- data.frame(B = c("Radiation therapy", "hello2 for neurology")) 

Ensuite, le code de sous les chaînes que vous voulez de la colonne B du dataframe:

df$B <- gsub("Radiation | for.*", "", df$B) 
0

Essayez ce qui suit.

dat <- 
structure(list(A = c("hello", "Hello1"), B = c("Radiation therapy", 
"hello2 for neurology"), C = c(NA, "hello3 radiation")), .Names = c("A", 
"B", "C"), row.names = c(NA, -2L), class = "data.frame") 

dat[] <- lapply(dat, function(x) gsub("radiation|for.*", "", x, ignore.case = TRUE)) 
dat 
     A  B  C 
1 hello therapy <NA> 
2 Hello1 hello2 hello3