我正在尝试使用两个参数(变量,值)来执行功能。该函数返回数据帧值的频率。我编写了以下代码,但它返回错误:找不到对象“变量”。有什么想法吗?在控制台中逐步执行此操作似乎是可行的,但在功能内却行不通。
data <- data.frame(SEX = c("MASCULINO", "FEMENINO", "FEMENINO","FEMENINO",
"MASCULINO", "FEMENINO", "FEMENINO","FEMENINO",
"MASCULINO", "FEMENINO", "FEMENINO","FEMENINO",
"MASCULINO", "FEMENINO", "FEMENINO","FEMENINO",
"MASCULINO", "FEMENINO", "FEMENINO","FEMENINO"),
AGE = c(33, 33, 45, 56, 76, 45, 45, 23, 56, 45,
19, 23, 45, 56, 28, 36, 53, 49, 47, 22))
value_frequency <- function(variable, value){
variable <- data$variable
table <- table(data$variable)
frequency<- table[[value]]}
value_frequency (SEX, FEMENINO)
Error in frecuencia_valor(SEXO, FEMENINO) : object 'FEMENINO' not found
答案 0 :(得分:1)
尝试一下:
value_frequency <- function(variable, value){
variable <- data[,variable]
table <- table(variable)
frequency <- table[value]
return(frequency)
}
value_frequency ("SEX", "FEMENINO")
FEMENINO
15
或更短一点,只返回值,而不返回关联的名称:
value_frequency <- function(variable, value){
return(table(data[,variable])[[value]])
}