R ';选择未定义的列';从2';对于循环';至';外部';

R ';选择未定义的列';从2';对于循环';至';外部';,r,dataframe,R,Dataframe,我有两个表:freq.table有每个土地类型的分布,match.table说明了哪些类型匹配 #freq.table #match.table typeA typeB | typeA typeB aland 30.0 70.0 | typeA TRUE TRUE bland 70.0 30.0 | typeB TRUE FALSE 现在我需要一个新的表,如freq.table,但具有不同

我有两个表:
freq.table
有每个土地类型的分布,
match.table
说明了哪些类型匹配

#freq.table               #match.table
       typeA  typeB   |         typeA typeB  
aland   30.0   70.0   |   typeA  TRUE  TRUE
bland   70.0   30.0   |   typeB  TRUE FALSE
现在我需要一个新的表,如
freq.table
,但具有不同的值:
对于
freq
(国家/地区,类型)中的每个点,新值应为所有(国家/地区,类型_m)的总和,其中(类型,类型_m)在match.table中为真。
你也可以说我想合并
freq[country,]
match[type,]
匹配类型的频率,但仅匹配
match
TRUE
的列
所以在
matches
中,我存储匹配类型,并且
freq[country,matches]
提供我需要的所有频率

match_table = read.table(file='donor_for.table', header=T, stringsAsFactors = FALSE)
freq        = read.table(file='frequency.table', header=T, stringsAsFactors = FALSE)

fill_table <- function(FUN){     
  newfr <-freq
  for (country in rownames(freq)){
    for (type in colnames(freq)){
      newfr[country, type] <- FUN(country, type)
    }
  }
  return(newfr)
}

fill_table2 <- function(FUN){    
  newfr <-freq
  newfr[] <- outer(rownames(freq), colnames(freq), FUN=FUN)
  return(newfr)
}

find_donor <- function(country, type_receiver) {
  matches=colnames(match_table)[match_table[type_receiver,]==TRUE]
  return( sum(freq[country,matches]) )    #24
}

你需要提供更多的解释。使用
dput
显示一些实际数据和您想要的输出。在第二个函数中,您使用的是
FUN=round
,舍入适用于数字列,这里的行名和列名是字符。抱歉,不清楚。@akrun我想我需要一个参数
FUN
的默认值。显然我不知道,所以我把它删掉了。
 Error in `[.data.frame`(freq, country, matches) : 
  undefined columns selected 
6 stop("undefined columns selected") 
5 `[.data.frame`(freq, country, matches) at blood.r#24
4 freq[country, matches] at blood.r#24
3 FUN(X, Y, ...) 
2 outer(rownames(freq), colnames(freq), FUN = FUN) at blood.r#18
1 fill_table2(find_donor)