在R中,我需要编写一个应用以下规则的函数:
fkt <- function(v1,v2){
- find list name within listOfLists that contains v1
- go to column in df, where listname == colname
- return value from row where df$col2 == v2
}
例如:
df <- data.frame(Col1= c(1,2,3,4,5),
Col2= c("AAA","BBB","CCC","DDD","EEE"),
A = c("22","22","23","23","24"),
B = c("210","210","202","220","203"),
C = c("2000","2000","2010","2010","2200")
)
listOflists <- list(A <- c(1281, 1282, 1285, 1286, 1289),
B <- c(100,200,300,400,500,600,700,800,900,101,202,303,404,505,606),
C <-c(1000,1500,2000,2500,3000,3050,4000,4500,6000)
)
然后
fkt(800,"BBB")
> 210
我尝试过
fkt<- function(v1,v2){
r <- which(df$Col2== v1)
s <- ifelse(v2 %in% A, df$A[r],
ifelse( v2 %in% B ,df$A[r],df$C[r]))
return(s)
}
A,结果是NA。 而且编写许多ifelse()语句效率不高-尤其是因为listOfLists可能包含50多个列表。
有人可以建议我如何如上所述以一种通用的,编程有效的方式编写此函数吗?
答案 0 :(得分:2)
df <- data.frame(Col1= c(1,2,3,4,5),
Col2= c("AAA","BBB","CCC","DDD","EEE"),
A = c("22","22","23","23","24"),
B = c("210","210","202","220","203"),
C = c("2000","2000","2010","2010","2200"))
# Be cautious : = and <- are not equivalent, you were creating variables not named fields
listOflists <- list(A = c(1281, 1282, 1285, 1286, 1289),
B = c(100,200,300,400,500,600,700,800,900,101,202,303,404,505,606),
C = c(1000,1500,2000,2500,3000,3050,4000,4500,6000))
f <- function(v1)
for (i in 1:length(listOflists))
if (v1 %in% listOflists[[i]]) return(names(listOflists)[i])
fkt <- function(v1,v2) df[df$Col2==v2,f(v1)]
fkt(800,"BBB")
#[1] 210
#Levels: 202 203 210 220