2017-09-18 50 views
0

假設我有中的R日曆狀數據幀:提取元件由索引

df = data.frame(Sun = c("*","*","*","*","*","*","*","*","*","*"), 
      Mon= c("*","s","*","*","*","*","*","*","*","*"), 
      Tues = c("*","*","*","*","*","*","*","*","*","*"), 
      Wedn = c("*","*","*","*","*","*","*","*","*","*"), 
      Thur = c("*","*","*","*","*","*","*","*","*","*"), 
      Fri = c("*","*","*","*","*","*","*","*","*","*"), 
      Sat = c("*","*","*","*","e","*","*","*","*","*")) 

> df 
    Sun Mon Tues Wedn Thur Fri Sat 
1 * * * * * * * 
2 * s * * * * * 
3 * * * * * * * 
4 * * * * * * * 
5 * * * * * * e 
6 * * * * * * * 
7 * * * * * * * 
8 * * * * * * * 
9 * * * * * * * 
10 * * * * * * * 

我們可以索引此日曆如下:

df_index[1,1] = 1 
df_index[1,2] = 2 
. 
. 
. 
df_index[2,1] = 8 
df_index[2,2] = 9 

等等等等。也就是說,df [1,1]是第一天,df [2,1]是第8天。 (並且df_index [,]不存在,只是爲了更好地理解)。

我想要做的是按索引子集這個數據幀。例如,我想從9日提取到第35天,並生成新的數據幀:

Sun Mon Tues Wedn Thur Fri Sat 
1 NA s * * * * * 
2 * * * * * * * 
3 * * * * * * * 
4 * * * * * * e 
+0

你只是想做到這一點:df [1:5,1:3]? –

+0

是的....我知道了......謝謝@Ben_its – skyindeer

回答

0

一個星期是什麼,而7天,以便通過7.考慮讓你不得不把它的週數作爲索引和提取子集的上限值應該工作!

> df[ceiling(9/7):ceiling(35/7),] 
    Sun Mon Tues Wedn Thur Fri Sat 
2 * s * * * * * 
3 * * * * * * * 
4 * * * * * * * 
5 * * * * * * e 
0

您可以矢量化數據幀,使得該向量的第一個元素是第一天,等

> x = as.vector(t(df)) 
    > x 
    [1] "*" "*" "*" "*" "*" "*" "*" "*" "s" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" 
    [20] "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "e" "*" "*" "*" 
    [39] "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" 
    [58] "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" 

要獲得9〜35天,你根本就

> x[9:35] 
[1] "s" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" "*" 
[20] "*" "*" "*" "*" "*" "*" "*" "e" 

然後,您可以再次將它放在矩陣/數據框中。但是,如果您錯過了本週的第一天,您還需要首先獲得NA值。所以可能應該使用天花板/樓層併除以7,正如其他答案所建議的那樣。