2015-10-27 70 views
0

我的數據幀稱爲d:你如何子集的數據幀基於變量名

dput(d) 
structure(list(Hostname = structure(c(8L, 8L, 9L, 5L, 6L, 7L, 
1L, 2L, 3L, 4L), .Label = c("db01", "db02", "farm01", "farm02", 
"tom01", "tom02", "tom03", "web01", "web03"), class = "factor"), 
    Date = structure(c(6L, 10L, 5L, 3L, 2L, 1L, 8L, 9L, 7L, 4L 
    ), .Label = c("10/5/2015 1:15", "10/5/2015 1:30", "10/5/2015 2:15", 
    "10/5/2015 4:30", "10/5/2015 8:30", "10/5/2015 8:45", "10/6/2015 8:15", 
    "10/6/2015 8:30", "9/11/2015 5:00", "9/11/2015 6:00"), class = "factor"), 
    Cpubusy = c(31L, 20L, 30L, 20L, 18L, 20L, 41L, 21L, 29L, 
    24L), UsedPercentMemory = c(99L, 98L, 95L, 99L, 99L, 99L, 
    99L, 98L, 63L, 99L)), .Names = c("Hostname", "Date", "Cpubusy", 
"UsedPercentMemory"), class = "data.frame", row.names = c(NA, 
-10L)) 

在一個循環,我需要去通過基於指標變量這個數據幀,我需要createa子集數據框架總結:

metrics<-as.vector(unique(colnames(d[,c(3:4)]))) 

for (m in metrics){ 
    sub<-dd[,c(1,m)] 
} 

我不能在這個子集線使用男,任何想法我可以如何根據變量名子集數據幀?


+1

您正在將索引子集'1'與'metrics'中的列名稱混合在一起。挑一個或另一個。可以使用第一列'[,c(「Hostname」,m)]'或所有索引'[,c(1,3,4)]' –

+0

的名稱。另外,如果您知道需要第三個和第四列爲什麼不是'for(m in 3:4)print(d [,c(1,m)])'unique/as.vector'包裝是什麼? –

回答

1

在你的子集調用中,你正在混合列索引和列名,所以R不明白你想要做什麼。

無論使用的列名:

for (m in metrics) { 
    sub <- d[, c(colnames(d)[1], m)] 
} 

或索引:

for (i in 3:4) { 
    sub <- d[, c(1, i)] 
} 

話雖如此,對於R中循環通常適用於需要動態分配的情況下,或致電副作用功能或者其他一些比較特殊的情況。通過在for循環中對數據進行切片和切塊來創建摘要幾乎從來都不是在R中執行它的正確方法。如果通常的功能工具不夠用,那麼可以使用plyr,dplyr等奇妙的包來分割應用,數據以非常方便和習慣的方式。