我有这样的事情:
#data.table
# a b
#aland 1 2
#bland 3 4
freq_all = read.table(file='data.table', header=T,stringsAsFactors = FALSE)
country_names = rownames(freq_all)
blood_types = colnames(freq_all)
func <- function(country,type) {paste(country, type)}
newfr <- freq_all
for (country in country_names){
for (type in blood_types){
newfr[country, type] <- func(country, type)
}
}
我想知道我是否可以使用apply()
函数或类似的东西。
答案 0 :(得分:1)
我们可以使用outer
freq1 <- freq_all
freq1[] <- outer(rownames(freq_all), colnames(freq_all), FUN= paste)
freq1
# a b
#aland aland a aland b
#bland bland a bland b
identical(freq1, newfr)
#[1] TRUE
freq_all <- structure(list(a = c(1L, 3L), b = c(2L, 4L)), .Names = c("a",
"b"), class = "data.frame", row.names = c("aland", "bland"))