mina
mina

Reputation: 195

Select a numeric columns of a dataframe in a list

I have a list of dataframes. After applying a function I get new columns that are non numeric. From each resulting dataframe that I save in a list modified_list As a result I want to save my modified dataframes but I only want to save the columns that contain numeric values. I am stocked in the selection of numeric columns. I do not know how to select numeric columns on a list of dataframes. My code looks something like this. Please do you have any idea what can i do to make this code work?

library(plyr)
library(VIM)

data1 <- sleep
data2 <- sleep
data3 <- sleep 
# get a list of dataframes
list_dataframes <- list(data1, data2, data3)  # list of dataframes
n <- length(list_dataframes)
# apply function to the list_dataframes
modified_list <- llply(list_dataframes, myfunction)
# selects only numeric results 
nums <- llply(modified_list, is.numeric) 

# saving results
for (i in 1:n){
        write.table(file = sprintf( "myfile/%s_hd.txt", dataframes[i]), modified_list[[i]][, nums], row.names = F, sep=",")
}

Upvotes: 0

Views: 1196

Answers (1)

effel
effel

Reputation: 1421

It sounds like you want to subset each data.frame in a list of data.frames to their numeric columns.

You can test which columns of a data.frame called df are numeric with

sapply(df, is.numeric)

This returns a logical vector, which can be used to subset your data.frame like this:

df[sapply(df, is.numeric)]

Returning the numeric columns of that data.frame. To do this over a list of data.frames df_list and return a list of subsetted data.frames:

lapply(df_list, function(df) df[sapply(df, is.numeric)])

Edit: Thanks @Richard Scriven for simplifying suggestion.

Upvotes: 5

Related Questions