[英]Creating a data.frame with rows from a function that returns vectors
我在多個單獨的csv文件中都有數據,我想為每個文件創建一個帶一行的data.frame。 下面的函數提供了每一行要使用的數據。 我不想更改此代碼,例如在輸出向量中包含Farmid部分。
vectorfromfile <- function(farmid) {
# Reads data from a file named farm{id}.csv, eg
# farm001.csv, and returns one named vector
# of length two with class numeric and names 'apples'
# and 'oranges' An example could be c(apples=4, oranges=6)
# The line below is a dummy for test purposes
c(apples=farmid+1000, oranges=farmid+2000)
}
然后,我有一個向量,即Farmid,例如Farmids <-c(1,3,5)。 我需要創建一個包含三列的數據框:id,蘋果和橘子,以及每個Farmid的一行。 它看起來應該像下面定義的data.frame。
> data.frame(id=c(1,3,5), apples=c(4,2,3), oranges=c(6,5,2) )
id apples oranges
1 1 4 6
2 3 2 5
3 5 3 2
我發現這樣做的幾種方法,它們都非常丑陋,占用很多行。 但我想使用拆分應用合並方法以最優雅的方式做到這一點。 所以我希望我可以簡單地申請(迭代)一個向量,並得到一個data.frame作為結果。 就像是
apply(farmids, ???? ) # farmids is a vector
那可能嗎? 如果沒有,那么也許遍歷具有相同值的列表? 如果不可能,那是最優雅的方式。
vect2df_v1 <- function(farmids=c(1,3,5)) {
df <- data.frame(id=farmids, apples=rep(NA, length(farmids)), oranges=rep(NA, length(farmids)))
for (i in 1:length(farmids)) {
df[i, c('apples', 'oranges')] <- vectorfromfile(df[i, 'id'])
}
df
}
vect2df_v2 <- function(farmids=c(1,3,5)) {
# Obviously it could be written into one (even uglier) line
farmrow <- function(farmid) { c(farmid, vectorfromfile(farmid)) }
lst <- lapply(farmids, farmrow)
mtrx <- matrix(unlist(lst), ncol=3, byrow=T, dimnames=list(NULL,c('id', 'apples','oranges')))
data.frame(mtrx)
}
使用do.call(rbind, ...)
很簡單。
您可以這樣編寫vect2df
:
vect2df <- function(vec) {
data.frame(id = vec, do.call(rbind, lapply(vec, vectorfromfile)))
}
演示:
vect2df(c(1, 3, 5))
# id apples oranges
# 1 1 1001 2001
# 2 3 1003 2003
# 3 5 1005 2005
當然,只需使用within
,就可以直接完成所有操作(如果vectorfromfile
不是關鍵函數,但可以簡單定義。
例:
within(data.frame(id = c(1, 3, 5)), {
oranges <- id + 2000
apples <- id + 1000
})
# id apples oranges
# 1 1 1001 2001
# 2 3 1003 2003
# 3 5 1005 2005
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.