Better way of adding data.frame columns by referring to indeces

℡╲_俬逩灬. 提交于 2019-12-24 06:43:14

问题


This question seems basic but I have not been able to find an answer to it.

I want to add columns of a data.frame together by just referring to their indeces.

Suppose I want to add columns 1,2, and 4.

df <- data.frame(
  a=rep(1, 5),
  b=rep(2, 5),
  c=rep(3, 5),
  d=rep(4, 5)
)

I know that explicitly referring to the column names I can do

> df$a + df$b + df$d
[1] 7 7 7 7 7

And referring to indeces I can do

> df[1] + df[2] + df[4]
  a
1 7
2 7
3 7
4 7
5 7

However, the index option above requires me to write out the name of the data.frame for every column I want to add.

Is there a way to add these columns together while just referring to the indeces and the data.frame once?


回答1:


You can use the rowSums function and refer to columns by setting a vector of column numbers in df[, ].

rowSums(df[, c(1,2,4)]
[1] 7 7 7 7 7



回答2:


Or within a data.table:

dt[, sum := rowSums(.SD), .SDcols = c(1, 2, 4)]
dt[, sum := rowSums(.SD), .SDcols = c('a', 'b', 'd')]



回答3:


with(df, a + b + d)
[1] 7 7 7 7 7



回答4:


Another solution using data.table:

require(data.table)  # Load package
dt <- data.table(df) # Convert to data.table
dt[, a + b + d]      # Sum columns
[1] 7 7 7 7 7  



回答5:


Another option is

Reduce(`+`, df[-3])
#[1] 7 7 7 7 7

Or a variant of @PierreLafortune

df$a + df$b + df$d
#[1] 7 7 7 7 7


来源:https://stackoverflow.com/questions/38594808/better-way-of-adding-data-frame-columns-by-referring-to-indeces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!