Carol.Kar
Carol.Kar

Reputation: 5345

Add text to one column of data.frame

I would like to add a text only to one column.

I tried the following(here as an example):

employee <- c('John Doe','Peter Gynn','Jolie Hope')
addMe <- c('test1','test2','test3')
salary <- c(21000, 23400, 26800)
dat <- data.frame(employee, salary, addMe)

dat[] <- lapply(dat$addMe, function(x) paste(' Please delete this col!', x))

However, my result frame looks like the following:

     employee                            salary                          addMe
1    Please delete this col! John Doe    Please delete this col! 21000   Please delete this col! test1
2    Please delete this col! Peter Gynn  Please delete this col! 23400   Please delete this col! test2
3    Please delete this col! Jolie Hope  Please delete this col! 26800   Please delete this col! test3

However I would like to have as a result:

    employee      salary        addMe
1   John Doe      21000         Please delete this col! test1
2   Peter Gynn    23400         Please delete this col! test2
3   Jolie Hope    26800         Please delete this col! test3    

Any suggestions what I am doing wrong?

I appreciate your replies!

Upvotes: 4

Views: 17661

Answers (2)

Mike Wise
Mike Wise

Reputation: 22807

You need the sapply, not the lapply:

employee <- c('John Doe','Peter Gynn','Jolie Hope')
addMe <- c('test1','test2','test3')
salary <- c(21000, 23400, 26800)
dat <- data.frame(employee, salary, addMe)


dat$addMe <- sapply(dat$addMe, function(x) paste(' Please delete this col!', x))

dat

Yielding:

> dat
    employee salary                          addMe
1   John Doe  21000  Please delete this col! test1
2 Peter Gynn  23400  Please delete this col! test2
3 Jolie Hope  26800  Please delete this col! test3

Upvotes: 3

doctorG
doctorG

Reputation: 1731

Just run

dat$addMe <- paste0("Please delete this col! ", dat$addMe)

in place of your lapply line.

Upvotes: 8

Related Questions