Citizen
Citizen

Reputation: 121

Extract the last column from a list of data frames

I have a list with ten data frames with different number of columns and I would like to get a list with ten vectors. Each vector would be the last column from each data frame.

If I want to get the last column from the first data frame, I run:

lapply(list_with_df,function(x) x[,lengths(list_with_df)[1]])

But I have got the same column number for each data frame.

I have tried to do a "loop for" through the ten data frames, but I have got an error. I appreciate if someone could help me with this matter. Regards.

Upvotes: 2

Views: 1338

Answers (1)

storaged
storaged

Reputation: 1847

Instead of using the lengths you can ask of the number of columns by ncol. This should work:

lapply(list_with_df,function(x) x[,ncol(x)])

Edit

Just for some clarification: The reason why you got the same column number for each data frame is because you have always selected the column number according to the first element of lengths vector by using lengths(list_with_df)[1]. It was always the length of the first data.frame

Upvotes: 2

Related Questions