2016-04-19 5 views
0

私は、異なる季節からサンプルを取ったデータフレームを持っています。私が望むのは、春(3月〜5月)と秋(9月〜11月)のサンプルが異なる年にどのようにサンプルされているかを要約することです。たとえば、サイトAに春2007のサンプルがある場合、セルには「TRUE」と表示されます。特定の変数の有無に基づいてTRUE/FALSEデータフレームを作成します

Dates <- data.frame(c(as.Date("2007-9-1"), 
        rep(as.Date("2008-3-1"), times = 3) , 
        rep(as.Date("2008-9-1"), times = 3))) 
Sites <- as.data.frame(as.factor(c("SiteA",rep(c("SiteA","SiteB","SiteC"), 2)))) 
Values <- data.frame(matrix(sample(0:50, 3.5*2, replace=TRUE), ncol=1)) 
Dataframe <- cbind(Dates,Sites,Values) 
colnames(Dataframe) <- c("date","site","value") 

私はこれらの機能に基づいてこのデータフレーム内の要素を作成することができました。

Dataframe$Months <- as.numeric(format(Dataframe$date, '%m')) 
Dataframe$Season <- cut(Dataframe$Months, 
        breaks = c(1, 2, 5, 8, 11, 12), 
        labels = c("Winter", "Spring", "Summer", "Autumn", "Winter"), 
        right = FALSE) 

ここからどこに行くのかはわかりません。出力は次のようになります。ここで

A <- rep("TRUE",times = 3) 
B <- c("FALSE",rep("TRUE",times = 2)) 
C <- c("FALSE",rep("TRUE",times = 2)) 

Output <- as.data.frame(rbind(A,B,C)) 
colnames(Output) <- c("Autumn.07","Spring.07","Autumn.08") 

答えて

1

は命題である:

reshape2を使用して
Dataframe$Samplings <- interaction(Dataframe$Season, unlist(lapply(strsplit(as.character(Dataframe$date), '-'), function(x) x[[1]]))) 

u1 <- unique(Dataframe$site) 
u2 <- unique(Dataframe$Samplings) 

output <- matrix(
    matrix(levels(interaction(u1, u2)), nrow=length(unique(Dataframe$site))) %in% 
    interaction(Dataframe$site,Dataframe$Samplings), 
    nrow=length(unique(Dataframe$site)) 
) 

colnames(output) <- levels(Dataframe$Samplings) 
rownames(output) <- unique(Dataframe$site) 
output # with all time interactions 
# you can clear it with 
output[, apply(output, 2, sum) != 0] 
+0

ありがとうございます! –

1

:: dcast

Dataframe$site <- gsub("Site","",Dataframe$site) 
Dataframe$year <- format(Dataframe$date, "%y") 
temp <- reshape2::dcast(Dataframe, site ~ Season + year, length) 
(ans <- apply(data.frame(temp[,2:ncol(temp)], row.names=temp[,1]), 1:2, as.logical)) 

ラベルを重複するため、あなたのデータフレーム$シーズンとの警告があります。それを修正したいかもしれません。

1

私はこれがあなたが探しているものだと思います。時間ラベルは質問とまったく同じではありませんが、それはまだ理解できると思います。

library(reshape2) 

# prepare the input, to have a handy label for the columns 
Dataframe$Year <- as.numeric(format(Dataframe$date, '%Y')) 
Dataframe$TimeLabel <- paste0(Dataframe$Season, '.', Dataframe$Year) 

# This is in stages, to make it clear what's happening. 

# create a data frame with the right structure, but cells holding NA/numbers 
df1 <- dcast(Dataframe, site ~ TimeLabel) 

# turn NA/number into false/true, while ignoring the site column 
df2 <- !is.na(df1[, -1]) 

# add back the site labels for rows 
df3 <- cbind(as.data.frame(df1$site), df2) 
+0

これは素晴らしいことです - 華麗に説明してくれてありがとう! –

+0

実際にステージ1〜3をマージすることができます: 'df3 < - dcast(Dataframe、site〜TimeLabel、fun.aggregate = function(x)length(x)> 0)' –

関連する問題