2016-12-02 44 views
1

我可以添加列data.frame:如何將多個空列添加到0行的data.frame?

x <- head(iris) 
y <- x[1:nrow(x) > 7, ] 
x[c('NewCol1', 'NewCol2')] <- rep(c('a', 'b'), each = nrow(x)) 

對於0排data.frame,這是行不通的:

# > y 
# [1] Sepal.Length Sepal.Width Petal.Length Petal.Width Species  
# <0 rows> (or 0-length row.names) 

y[c('NewCol1', 'NewCol2')] <- rep(c('a', 'b'), each = nrow(y)) 

# Error in value[[jvseq[[jjj]]]] : subscript out of bounds 

我發現這一點,Add Columns to an empty data frame in R,但它不幫助很大。

預期輸出:

# > y 
# [1] Sepal.Length Sepal.Width Petal.Length Petal.Width Species  NewCol1  NewCol2 
# <0 rows> (or 0-length row.names) 
+0

我不明白'y'是否屬於空數據框。它有內容。你能詳細說明你在這裏做什麼嗎? –

+1

@TimBiegeleisen,很抱歉。我編輯了這個問題。 – mt1022

+0

所以你有'x'作爲6行的數據框。你的預期產出是多少? –

回答

2

考慮創建空數據幀以下代碼:

df <- data.frame(Ints=integer(), 
       Characters=character(), 
       stringsAsFactors=FALSE) 

一種方式將新的列添加到該空數據幀是使用cbind()

df2 <- cbind(df, data.frame(Stuff=character(),stringsAsFactors=FALSE)) 

> df2 
[1] Ints  Characters Stuff  
<0 rows> (or 0-length row.names) 

然後,只需像往常一樣添加您的數據,e 。G。

> df2[1,] <- c(1, "hello", "world") 
> df2 
    Ints Characters Stuff 
1 1  hello world 

如上所述,這可能會在Ints列中導致鑄造問題。分配每一列避免了這一點,例如

df2$Ints <- c(1:5) 
df2$Stuff <- c("one", "two", "three", "four", "five") 

或者,你可以使用類似read.table在數據帶上,並且明確指定的類的方式。

+0

這工作。但是'f2 [1,] < - c(1,「hello」,「world」)'把Ints col改成了字符! – mt1022

+0

無論如何,我接下來要做的是對由lapply生成的data.frames進行綁定(有些是空的)。這很重要。 – mt1022

2

我們可以通過設置col.names參數使用read.table

read.table(text = "",col.names = c(names(y), c("New_Col1", "New_Col2"))) 

#Sepal.Length Sepal.Width Petal.Length Petal.Width Specie New_Col1 New_Col2 
#<0 rows> (or 0-length row.names) 

我們還可以設置使用colClasses參數

read.table(text = "",col.names = c(names(y), c("New_Col1", "New_Col2")), 
       colClasses = c(sapply(y, class), "character", "character")) 

因此,在這種情況下,兩個新的變量將得到character類我們所期望的類。