ddply:如何将列名作为参数传递? [英] ddply: how do I pass column names as parameters?
问题描述
我有一个数据框,其中的列名称是根据参数生成的-因此我不知道它们的确切值.我想将这些字段也作为参数传递给ddply. 我想答案很明显,但是有人可以帮我打开灯.
I have a data frame where the column names are generated based on parameters - so I don't know their exact values. I want to pass these fields to ddply also as parameters. I guess the answer is obvious, but can someone please turn the light on for me.
下面的示例使用虹膜数据集,它给出了我想做的事情的想法,以及我所付出的努力的意外结果.第一个示例的结果是我要实现的虹膜1,但是通过将列名作为参数传递(如我的虹膜2所做的那样),这并没有达到我想要的结果.
Example below using the iris data set that gives the idea of what I want to do, and the unintended result of my effort. The results of first example, iris1 is what I want to achieve, but by passing the column names in as parameters, as in my iris2 effort, that doesn't give me the intended results.
iris1 <- ddply(iris, .(Species), transform, pw_first = Petal.Width[1],
pw_last = Petal.Width[length(Petal.Width)])
myCol <- 'Petal.Width'
iris2 <- ddply(iris, .(Species), transform, pw_first = myCol[1],
pw_last = myCol[length(myCol)])
head(iris1)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species pw_first pw_last
# 1 5.1 3.5 1.4 0.2 setosa 0.2 0.2
# 2 4.9 3.0 1.4 0.2 setosa 0.2 0.2
# 3 4.7 3.2 1.3 0.2 setosa 0.2 0.2
# 4 4.6 3.1 1.5 0.2 setosa 0.2 0.2
# 5 5.0 3.6 1.4 0.2 setosa 0.2 0.2
# 6 5.4 3.9 1.7 0.4 setosa 0.2 0.2
head(iris2)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species pw_first pw_last
# 1 5.1 3.5 1.4 0.2 setosa Petal.Width Petal.Width
# 2 4.9 3.0 1.4 0.2 setosa Petal.Width Petal.Width
# 3 4.7 3.2 1.3 0.2 setosa Petal.Width Petal.Width
# 4 4.6 3.1 1.5 0.2 setosa Petal.Width Petal.Width
# 5 5.0 3.6 1.4 0.2 setosa Petal.Width Petal.Width
# 6 5.4 3.9 1.7 0.4 setosa Petal.Width Petal.Width
推荐答案
colName<-"Petal.Width"
iris1 <- ddply(iris, .(Species), function (x) {
pw.first=x[1,colName]
pw.last=x[length(x[,1]),colName]
result=cbind(x,pw.first,pw.last)
return(result)})
unique(iris1$pw.first)
[1] 0.2 1.4 2.5
unique(iris1$pw.last)
[1] 0.2 1.3 1.8
如果只需要种类,然后是pw.first和pw.last,只需从cbind中删除x.
If you only want the species, and pw.first and pw.last, simple remove the x from cbind.
这篇关于ddply:如何将列名作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!