2015-01-19 2 views
0

어쨌든, 나는 내 질문을 simplfy.data.frame의 레코드를 매개 변수로 함수에 전달하는 방법은 무엇입니까?

for (i in 1:3) { 
    f(dt$x[i], dt$y[i]) 
    } 
: 나는 다음과 같은 위해 루프 사용할 수 있습니다 알고

f(1, "a") 
    f(2, "b") 
    f(3, "c") 

:

dt <- data.frame(x=c(1,2,3), y=c("a", "b", "c")) 
f <- function(x, y){ 
    #f is a function that only take vector whose length is one. 
} 

그래서 나는 다음과 같은 F 기능을 사용할 필요가 : 우리는이 같은 dataframe이

하지만 바보 같고 추한 것 같습니다. 그런 작업을 수행하는 더 좋은 방법이 있습니까?

+0

'f'라는 함수의 결과로 예상되는 결과는 무엇입니까? –

+0

이 이전 질문은 읽을만한 가치가 있습니다. [df의 각 행에서 여러 개의 인수를 사용하여 dataframe의 각 행에 apply-like 함수를 호출하는 방법 (http://stackoverflow.com/questions/15059076/r-how- to-call-apply-like-function-on-each-row-of-dataframe-multiple-argum/15059295) – thelatemail

답변

1

하나의 옵션이 같이 vectorize 경우에 잘 작동 기능 f (즉, 벡터 반환 값)에 다음과 같습니다

# returs a vector of length 1 
f = function(x,y)paste(x[1],y[1]) 
# returs a vector with length == nrow(dt) 
Vectorize(f)(dt$x,dt$y) 

# returs a vector of length 2 
f = function(x,y)rep(x[1],1) 
# returns a matrix with 2 rows and nrow(dt) columns 
Vectorize(f)(dt$x,dt$y) 

f = function(x,y)rep(y[1],x[1]) 
# returns a list with length == nrow(dt) 
Vectorize(f)(dt$x,dt$y) 

아니라 다른 사람 (즉, 복합 반환 값 [목록]), 예 :

# returns a list 
f = function(x,y)list(x[1],y[1]) 
# returns a matrix but the second row is not useful 
Vectorize(f)(dt$x,dt$y) 
+0

많은 컬럼을 가진 데이터 프레임의 경우,'do.call (Vectorize f), dt)' –

관련 문제