我的任务是制定一种“约会算法”,在该算法中,我使用.csv文件加载所有用户,然后将其子集化为每个性别。 目前,我在if语句中
if(user_sexuality=="female"){
#compare females from subset
}else{
#compare men from subset
}
如果可能的话,我想使用变量而不是
删除此if语句female$age
male$age
这是我当前设置代码的方式:
users <- read.table("users.csv", sep=";", header = TRUE, stringsAsFactors = FALSE)
searching = read.table("searching.csv",sep=";", header = TRUE, stringsAsFactors = FALSE)
score <- read.table("score.csv",sep=";", header = TRUE, stringsAsFactors = FALSE)
male <- subset(users,gender=="male")
female <- subset(users,gender=="female")
#If we take example in user 1 who's interested in "female"
user_sexuality <- users$looking_for[1]
if(user_sexuality=="female"){
for(i in 1:nrow(female)){
if(female$age[i] > searching$minage[row_no] &
female$age[i] < searching$maxage[row_no]){
age_score <- score$age[1]
age_vec <- c(aget_vec,age_score)
}
}
}else{
#the exact same thing as in above but with male instead of female
}
当我将user_sexuality定义为“ female”时,我尝试了两种方法都不起作用。我在控制台中写了以下内容:
>user_sexuality$age
Error in user_sexuality$age : $ operator is invalid for atomic vectors
>cat(paste(user_sexuality,"$age[",1,"]",sep=""))
female$age[1]
如果我通常和女性一起做,我会得到我想要的东西:
>female$age[1]
[1] 19
答案 0 :(得分:0)
我认为这就是您想要的。
我不确定为什么需要解析,但是eval不能单独工作。
female <- data.frame( age = c(1,2,3) )
user_sexuality <- "female"
i <- 1
eval(parse(text=paste0(user_sexuality,"$age[",i,"]")))
[1] 1