R嵌套for循环合并数据帧

时间:2012-05-21 18:07:08

标签: r for-loop merge dataframe

我有一个数据框,其中每列是一个时间序列的数字(从0到8)代表动物求爱期间的不同行为。我想检查是否有一个模式,如给定的行为更频繁地由另一个行为。我编写了一个函数,允许我计算在特定时间间隔后遵循给定行为的行为频率:

> data[,3]
  [1]  1  1  1  1  7  7  3  3  7  3  1  1  8  1  3  3  3  5  1  1  4 ... 

neighbor <- function(DATA, BEHAVIOR, INTERVAL)
{
total=c(0)
tmp = data.frame(total=c(0:8),Freq=rep(0,9))
number_of_x = which(DATA == BEHAVIOR)

for(i in number_of_x){
              total = append(total,DATA[i+INTERVAL,])
}
tmp = merge(tmp,table(total), by=c("total"), all=T)
tmp[is.na(tmp)] <- 0
subset(tmp, select = ncol(tmp))
}

所以我运行函数说第三列,行为3,以及时间(1)中的下一个行为,我得到了我想要的东西:

> neighbor(as.data.frame(data[,3], 3, 1]
Freq.y
0 0.01
1 0.71
2 0.01
3 0.21
4 0.01
5 0.04
6 0.01
7 0.02
8 0.00

现在我想使用类似的函数来获得九种行为的频率。类似的东西:

neighborAll <- function(DATA, INTERVAL)
{
total=c(0)
tmp = data.frame(total=c(0:8),Freq=rep(0,9))
for(a in c(0:8)){
number_of_x = which(DATA == a)
for(i in number_of_x){
      total = c(total,DATA[i+INTERVAL,])
}
tmp=merge(tmp, table(total), by = c("total"), all=T)
tmp[is.na(tmp)] <- 0
}
tmp[,3:9]
}

> neighborAll(as.data.frame(data[,3], 1)

我明白了:

Error in merge.data.frame(tmp, table(total), by = c("total"), all = T) : 
  there is already a column named ‘Freq.x’

任何想法都会受到欢迎。提前谢谢,何塞

2 个答案:

答案 0 :(得分:1)

基本上你想要这个:

neighborAll <- function(DATA, INTERVAL, TABLE)
{
    for(i in 1:(nrow(TABLE) - 1))
    {
        neighbors <- DATA[which(DATA == i) + INTERVAL]
        tab <- table(neighbors)
        TABLE[TABLE$behavior %in% names(tab), i + 2] <- tab
    }
    return(TABLE)
}

x<-c(1, 1, 1, 1, 7, 7, 3, 3, 7, 3, 1, 1 ,8, 1, 3, 3, 3, 5, 1, 1, 4)

behavior <- 0:8
n <- length(behavior)
tmp <- matrix(nrow=n, ncol=n)
colnames(tmp) <- paste("freq", behavior, sep="")
freqtab <- data.frame(behavior, tmp)

neighborAll(x, 1, freqtab)

答案 1 :(得分:0)

如果没有正确的名称,那么每一个都可能是单行。

neighbor <- function(DATA, BEHAVIOR, INTERVAL) {
  nbins <- 1+max(0, DATA, na.rm = TRUE)
  out <- tabulate(1+DATA[which(DATA==BEHAVIOR)+INTERVAL], nbins=nbins)
  names(out) <- 1:nbins - 1
  out
}

neighborAll <- function(DATA, INTERVAL) {
  out <- sapply(0:max(DATA, na.rm=TRUE), 
         function(BEHAVIOR) neighbor(DATA, BEHAVIOR, INTERVAL))
  colnames(out) <- 0:max(DATA, na.rm=TRUE)
  out
}

> x <- c(1, 1, 1, 1, 7, 7, 3, 3, 7, 3, 1, 1 ,8, 1, 3, 3, 3, 5, 1, 1, 4)

> neighbor(x,3,1)
0 1 2 3 4 5 6 7 8 
0 1 0 3 0 1 0 1 0 

> neighborAll(x,1)
  0 1 2 3 4 5 6 7 8
0 0 0 0 0 0 0 0 0 0
1 0 5 0 1 0 1 0 0 1
2 0 0 0 0 0 0 0 0 0
3 0 1 0 3 0 0 0 2 0
4 0 1 0 0 0 0 0 0 0
5 0 0 0 1 0 0 0 0 0
6 0 0 0 0 0 0 0 0 0
7 0 1 0 1 0 0 0 1 0
8 0 1 0 0 0 0 0 0 0