更好地通过引用indeces来添加data.frame列 [英] Better way of adding data.frame columns by referring to indeces
问题描述
这个问题似乎是基本的,但我无法找到答案。
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.
假设我要添加1,2和4列。
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
指的是我可以做的事情
> 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.
有没有办法将这些列添加在一起,而只是引用indeces和 data.frame
一次?
Is there a way to add these columns together while just referring to the indeces and the data.frame
once?
推荐答案
可以使用rowSums函数并参考通过在 df [,]
中设置列号向量的列。
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
这篇关于更好地通过引用indeces来添加data.frame列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!