mardi 9 juin 2020

IF-sentence over all columns in a dataframe in R

I have a df, I would like R to paste 'Hi,' in front of the text, if a condition is fulfilled (if the column contains 'how are you').

t <- data.frame('x1' = c('how are you','whats up?', 'whats up?'), "x2" = c('how are you','how are you', 'whats up?'), "x3" = c('whats up?','how are you', 'whats up?'))

How can I do it for all the columns at the same time? I have tried with an if-sentence and lapply


#this doesn't work

t[] <- if(t[] %like% ('how are you')) {paste("Hi, ",t[])}

t[] <- lapply(t, function(x)  if(x %like% ('how are you')) {paste("Hi,",x)})

#this works, but then all other content is erased;

t[] <- lapply(t, function(x) 
                ifelse(x %like% ('how are you'), paste("Hi,", x),""))

thanks in advance!

Aucun commentaire:

Enregistrer un commentaire