2017-06-22 84 views
0

我想根據某些列中的值動態創建data.table的子集。R創建data.table的動態子集

在我的data.table中,我有以下變量:owner,2G,3G,4G。 2G,3G,4G是二進制的。

我想創建三個子集:一個是2G == 1,一個是3G == 1,一個是4G == 1。

例子:

a=c("Paul",1,1,0) 
b=c("George",1,0,0) 
x=cbind(a,b) 
colnames(x)=c("Owner","2G","3G","4G") 

這裏是我的代碼:

all_names_df=c() 

for(value in 2:4){ 
    techno=paste0(value,"G") 
    name=paste0("arcep",techno) 
    all_df=c(all_names_df,name) 
    df=arcep[techno==1] 
    assign(name,df) 
} 

創建我的新data.tables,而空。我已經嘗試了幾件事情(與評估,引用,更改語法等),但我沒有正確調用列。

編輯:

我曾嘗試別的東西,但它也失敗:

techno=c("2G","3G","4G") 
for(value in techno){ 
index=grep(value,colnames(arcep)) 
print(index) 
set1=subset(arcep,arcep[,index]==1) 
print(dim(set1)) 
assign(set1,paste0("ARCEP_",value))} 

Error in `[.data.table`(arcep, , index) : 
    j (the 2nd argument inside [...]) is a single symbol but column name 'index' is not found. Perhaps you intended DT[,..index] or DT[,index,with=FALSE]. This difference to data.frame is deliberate and explained in FAQ 1.1. 

爲什麼它說:「「列名‘索引’未找到」?爲什麼它不是考慮到「索引」的價值?評估指標不會改變任何東西。

+0

我試過別的: – Oolis

+0

你正在使用'data.table',所以'arcep [,index]'等同於''arcep [[「index」]]''。另外,你想用'assign'做什麼? –

回答

-1

我終於找到了答案:

for(value in techno){ 
    set1=subset(arcep,arcep[,get(colnames(arcep)[grep(value,colnames(arcep))])]==1) 
    assign(paste0("ARCEP_",value),set1) 
} 
2

矢量和矩陣不能同時包含數字和字符,在你的情況下數字被轉換爲字符。

這將更好地工作來定義你的表,但在data.frame列名不能以數字開頭

x <- data.frame(Owner = c("Paul","George"), 
       G2 = c(1,1), 
       G3 = c(1,0), 
       G4 = c(0,0), 
       stringsAsFactors= FALSE) 

那麼這裏就是你的子集

subset(x,G3 == 1) 

(也,你已使用cbind而不是在您的問題中,您可能要編輯它)

+0

謝謝,但它不能解決我的「動態」問題... – Oolis