Ted Mosby
Ted Mosby

Reputation: 1456

Truncate data.frames in a list to the shortest length

I have some data like so:

df1 = (cbind(c(1,2,3),c(4,5,7)))
df2= cbind(c(1,2,5,8,1,7),c(1,2,5,8,1,7))
myls=list(df1,df2)

I'm looking for a way to chop df2 to the length of d1. This can be done just by cutting off any numbers at the end of df2. Hopefully the solution would also allow for more than 2 df in the list. The real data set has 1.4mill points and some varying amount of dfs(df1,df2,df3....df(n). they all will only have 2 columns though(y) and (x).

My guess is that sapply(myls,'[',1) will be used..

Upvotes: 1

Views: 1049

Answers (2)

akrun
akrun

Reputation: 887158

We could also use the head

n <- min(vapply(myls, nrow, 0))
lapply(myls, head, n)

Upvotes: 2

David Heckmann
David Heckmann

Reputation: 2939

n <- min( sapply(myls, nrow ) )
lapply(myls, function(x){x[1:n,]})

Upvotes: 1

Related Questions