将文本添加到data.frame的一列

时间:2016-01-04 15:49:41

标签: r dataframe

我想只在一列添加文字。

我尝试了以下(此处为例):

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))

但是,我的结果框架如下所示:

     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

但是我希望得到结果:

    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    

有什么建议我做错了吗?

感谢您的回复!

2 个答案:

答案 0 :(得分:6)

跑步

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

取代你的lapply线。

答案 1 :(得分:2)

您需要Option Explicit Sub UpdateLogWorksheet() Dim historyWks As Worksheet Dim inputWks As Worksheet Dim nextRow As Long Dim oCol As Long Dim myRng As Range Dim myCopy As String Dim myCell As Range ActiveSheet.Unprotect "sallygary" 'cells to copy from Input sheet - some contain formulas myCopy = "g12,g14,g18,g20,g22,g24,i16,i18,i20,i22,i24,k16,k18,k20,k22,k24,m16,m18,m20,m22,m24,o16,o18,o20,o22,o24,q16,q18,q20,q22,q24,s16,s18,s20,s22,s24,u16,u18,u20,u22,u24" Set inputWks = Worksheets("Input") Set historyWks = Worksheets("1_Data") With historyWks nextRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row End With With inputWks Set myRng = .Range(myCopy) 'If Application.CountA(myRng) <> myRng.Cells.Count Then ' MsgBox "Please fill in all the cells!" ' Exit Sub 'End If End With With historyWks With .Cells(nextRow, "A") .Value = "e4" .NumberFormat = "mm/dd/yyyy" 'hh:mm:ss End With .Cells(nextRow, "B").Value = Application.UserName oCol = 3 For Each myCell In myRng.Cells historyWks.Cells(nextRow, oCol).Value = myCell.Value oCol = oCol + 1 Next myCell End With 'clear input cells that contain constants With inputWks On Error Resume Next With .Range(myCopy).Cells.SpecialCells(xlCellTypeConstants) .ClearContents Application.GoTo .Cells(1) ', Scroll:=True End With On Error GoTo 0 End With ActiveSheet.Protect "sallygary" Range("g12").Select End Sub ,而不是sapply

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