在数据框中添加新列

收藏

如果我想在数据框中添加新列(前两列的除数),这是正确的方法吗?

Newcolumn <- sum(Data$column1)/sum(Data$column2)
NewcolumnCol<- data.frame(Newcolumn,col.names=Newcolumn) 
allData <- merge(Newcolumn, Data)
回复
  • We can use transform instead of mergeing to directly create the column and update the 'Data'

    Data <- transform(Data, NewColumn = sum(column1)/sum(column2))
    

    或者只是通过分配来创建新列

    Data$NewColumn <- with(Data, sum(column1)/sum(column2))
    

    The division of sum of two columns returns a single and that gets recycled to the number of rows of the dataset with the assignment.

    merge is mostly done when we have two datasets with one or more columns to match while doing the assignment. Here, it is not the case