2016-10-10 2 views
1

После код могут быть использованы для создания data.frame с Кендалл-тау и Спирмен результатами корреляции рядом друг с другом:R: Включает цикл внутри функции?

data(mtcars) 
mtcars 

correlation <- function(x,y){ 
    df1 = cor(data.frame(x,y), use="complete.obs", method="kendall") 
    df2 = cor(data.frame(x,y), use="complete.obs", method="spearman") 
    return(data.frame(df1,df2)) 
} 

correlation(mtcars[1],mtcars[2]) 

Вопрос: Вместо того, чтобы цепочки команд, может что-то вроде петли для два методы быть реализованы?

methods <- ("kendall", "spearman") 

correlation <- function(x,y){ 
    df = cor(data.frame(x,y), use="complete.obs", method=methods) 
    return(data.frame(df)) 
} 

correlation(mtcars[1],mtcars[2]) 
#This should output the two results, just as above. 

Я пробовал список, но не был успешным.

ответ

0

Вы можете использовать инструкцию for. Просто сделайте следующее:

methods <- c("kendall", "spearman") 

    correlation <- function(x,y, methods){ 

     result <- list() 
     for (type in methods){ 

     df = cor(data.frame(x,y), use="complete.obs", method=type) 

     result[type] <- list(df) 
     } 

     return(data.frame(result)) 
    } 

    correlation(mtcars[1],mtcars[2],methods) 
+0

Я не могу воспроизвести этот скрипт. Ошибка: неожиданный ',' in 'методы <- ("kendall", "... Когда я делаю это список, он все еще отвечает" аргумент "методы" отсутствует, без значения по умолчанию " – DoeyFoey

+0

Исправлено, с' c() 'в первой строке и передать« методы »функции, для меня она работает сейчас. Извините, забыл адаптировать это. –

+0

Спасибо, это сработало! – DoeyFoey

0
# vector that has your methods 
methods <- c("kendall", "spearman") 

# function which loops thru the vector of functions 
correlation <- function(x,y) { 
    a <- lapply(X = methods, FUN = function(m,x,y){ 
    df1 = cor(data.frame(x,y), use="complete.obs", method= m) 
    },x=x,y=y) 

    return(a) 
} 

res <- correlation(mtcars[1],mtcars[2]) 
#list to dataframe 

do.call("cbind", lapply(res, as.data.frame)) 

Результаты:

  mpg  cyl  mpg  cyl 
mpg 1.0000000 -0.7953134 1.0000000 -0.9108013 
cyl -0.7953134 1.0000000 -0.9108013 1.0000000 

Спасибо!

+0

Ошибка в lapply (a, as.data.frame): объект 'a' не найден? – DoeyFoey

+0

Извините, исправлено. – Indi

Смежные вопросы