【问题标题】:Dynamically specify column name in spread()在 spread() 中动态指定列名
【发布时间】:2016-02-18 16:05:03
【问题描述】:

我正在尝试自动化一个简单的过程,即导入一些数据并使用 tidyr 包中的扩展函数使其成为宽格式数据。

下面是一个简化的例子

Ticker <- c(rep("GOOG",5), rep("AAPL",5))
Prices <- rnorm(10, 95, 5)

Date <- rep(sapply(c("2015-01-01", "2015-01-02", "2015-01-03", "2015-01-04", "2015-01-05"),as.Date), 2)

exStockData <- data.frame(Ticker, Date, Prices)

在读取 exStockData 之类的数据框后,我希望能够创建如下所示的数据框

library(tidyr)
#this is the data frame I'd like to be able to create
desiredDataFrame <- spread(exStockData, Ticker, Prices)

但是,用于扩展函数的键参数的列并不总是称为 Ticker,而用于函数的 value 参数的列也不总是称为价格。列名是从导入的文件的不同部分读入的。

#these vectors are removed because the way my text file is read in 
#I don't actually have these vectors
rm(Ticker, Prices, Date)

#the name of the first column (which serves as the key in 
#the spread function) of the exStockData data frame will 
#vary, and is read in from the file and stored as a one 
#element character vector
secID <- "Ticker"

#the name of the last column in the data frame 
#(which serves as the value in the spread function) 
#is stored also stored as a one element character vector
fields <- "Prices"

#I'd like to be able to dynamically specify the column 
#names using these other character vectors
givesAnError <- spread(exStockData, get(secID), get(fields))

【问题讨论】:

  • ?spread 的文档将您引向专门用于此目的的 ?spread_
  • 这既方便又尴尬。谢谢!
  • @user1583016,您可以发布解决方案作为您自己问题的答案并接受它,或者删除该问题。如果我没记错的话,这会记录在帮助文件中并作为小插曲的一部分。 (除非 joran 想发布答案....)
  • 我继续发布了答案。不过我不能再接受两天了。

标签: r tidyr


【解决方案1】:

spread 函数文档的“另见”部分提到了用于这种情况的 spread_ 函数。

在这种情况下,解决方案是使用:

solved <- spread_(exstockData, secID, fields)

【讨论】:

    猜你喜欢
    • 2016-12-17
    • 2019-04-29
    • 2012-02-05
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多