我想根據某些列中的值動態創建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.
爲什麼它說:「「列名‘索引’未找到」?爲什麼它不是考慮到「索引」的價值?評估指標不會改變任何東西。
我試過別的: – Oolis
你正在使用'data.table',所以'arcep [,index]'等同於''arcep [[「index」]]''。另外,你想用'assign'做什麼? –