调用函数时设置列名 [英] Set column names while calling a function
问题描述
考虑我们有一个数字数据框 foo
并且想要找到每两列的总和:
Consider we have a numeric data.frame foo
and want to find the sum of each two columns:
foo <- data.frame(x=1:5,y=4:8,z=10:14, w=8:4)
bar <- combn(colnames(foo), 2, function(x) foo[,x[1]] + foo[,x[2]])
bar
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 5 11 9 14 12 18
#[2,] 7 13 9 16 12 18
#[3,] 9 15 9 18 12 18
#[4,] 11 17 9 20 12 18
#[5,] 13 19 9 22 12 18
一切都很好,除了 bar
中缺少的列名.我希望 bar
的列名显示 foo
中的相关列,例如在这个例子中:
Everything is fine, except the column names that are missing from bar
. I want column names of bar
to show the related columns in foo
, for instance in this example:
colnames(bar) <- apply(combn(colnames(foo),2), 2, paste0,collapse="")
colnames(bar)
#[1] "xy" "xz" "xw" "yz" "yw" "zw"
这很简单,但我想在同一个 bar <- combn(...)
命令中执行列标记.有吗?
This is simple, but I want to perform column labeling in the same bar <- combn(...)
command. Is there anyway?
推荐答案
这是可能的,但它会混淆您的代码.此处简洁与清晰之间的权衡非常重要.
It is possible, but it obfuscates your code. The tradeoff between brevity and clarity here is acute.
要了解它是如何工作的,我参考了这个问题.
To understand how it works, I reference this question.
colnames(x) <- y
内部改写为
x <- `colnames<-`(x,y)
然后您可以自己进行翻译.
You can then do the translation yourself.
bar <- `colnames<-`(combn(colnames(foo), 2, function(x) foo[,x[1]] + foo[,x[2]]),
apply(combn(colnames(foo),2), 2, paste0,collapse=""))
然而,在许多情况下,以这种方式折叠代码行所需的心理和句法体操是不值得的.多条线往往更清晰.
In many cases, however, it's not worth the mental and syntactic gymnastics required to collapse lines of code in this way. Multiple lines tend to be clearer to follow.
这篇关于调用函数时设置列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!