Jcarl
Jcarl

Reputation: 161

Convert structure of columns in list of dataframes to character in R

I'm creating an empty list of dataframes that I will append later using lapply.

library(tidyverse)
library(dplyr)
library(purrr)

my.list <- lapply(1:192, function(x, nr = 468, nc = 1) {   data.frame(symbol = matrix(nrow=nr, ncol=nc)) })
str(my.list)

If you obtain the structure of my.list you will notice that the structure of the columns within each dataframe is "logical". I would like the structure of the column in each dataframe to be character rather than logical.

Can I change anything within my lapply function above so that the columns in the resulting list of dataframes are character? Or how best would I go about this task? I'm creating this empty list of dataframes because I understand that R works faster if it doesn't have to constantly append files. Thus my next step is to perform a map function to populate each dataframe in this list of dataframes with character data.

Upvotes: 1

Views: 567

Answers (1)

akrun
akrun

Reputation: 887691

The issue would be that by creating NA, by default it is NA_logical_. If we want to create a character column, use NA_character_. Here, we can fix with

my.list <- lapply(my.list, function(x) {x[] <- lapply(x, as.character); x})

Or while creating the data.frame column, use

my.list <- lapply(1:192, function(x) data.frame(symbol = rep(NA_character_, 468)))

The matrix route to get a single column data.frame is not ideal and is sometimes incorrect (because matrix can have only a single class whereas data.frame columns can be of different type). The easiest option is replicate the NA_character_ with n times to create a single column data.frame with n rows

Upvotes: 1

Related Questions