调用函数时设置列名 [英] Set column names while calling a function
问题描述
考虑到我们有一个数字data.frame foo
,并希望找到每两列的总和:
foo< - data.frame(x = 1:5,y = 4:8,z = 10:14,w = 8:4)
bar<组合(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
中的相关列,例如在此示例中:
colnames(bar)< - apply(combn(colnames(foo),2),2,paste0,collapse =)
colnames(bar)
#[1]xyxzxwyzywzw
这很简单,但我想在同一个 bar< - combn(...)
命令中执行列标签。有没有吗?
这是可能的,但它会混淆您的代码。为了理解它的工作原理,我参考了这个问题。
colnames(x)< - y
内部重写为
x< - `colnames< -`(x,y)
然后,您可以自己进行翻译。
bar< - `colnames< -`(combn(colnames(foo)) ,function(x)foo [,x [1]] + foo [,x [2]]),
apply(combn(colnames(foo),2),2,paste0,collapse =
然而,在许多情况下,这是不值得的精神和语法体操需要折叠代码行这条路。多行趋于更清晰。
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
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"
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
Is internally rewritten as
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屋!