Convert data.frame columns from factors to characters
Just following on Matt and Dirk. If you want to recreate your existing data frame without changing the global option, you can recreate it with an apply statement:
bob <- data.frame(lapply(bob, as.character), stringsAsFactors=FALSE)
This will convert all variables to class "character", if you want to only convert factors, see Marek's solution below.
As @hadley points out, the following is more concise.
bob[] <- lapply(bob, as.character)
In both cases, lapply
outputs a list; however, owing to the magical properties of R, the use of []
in the second case keeps the data.frame class of the bob
object, thereby eliminating the need to convert back to a data.frame using as.data.frame
with the argument stringsAsFactors = FALSE
.
Convert dataframe numeric column to character
I think you can do that and that should work :
coldata$Station<-as.character(coldata$Station)
convert all factor columns to character in a data.frame without affecting non-factor columns
You can try:
library(tidyverse)
d <- data.frame(a = 1:5,
b = factor(c("a", "b", "c", "d", "e")),
c = factor(c("f", "g", "h", "i", "j")))
d %>% glimpse()
Observations: 5
Variables: 3
$ a <int> 1, 2, 3, 4, 5
$ b <fctr> a, b, c, d, e
$ c <fctr> f, g, h, i, j
d %>%
mutate_if(is.factor, as.character) %>%
glimpse()
Observations: 5
Variables: 3
$ a <int> 1, 2, 3, 4, 5
$ b <chr> "a", "b", "c", "d", "e"
$ c <chr> "f", "g", "h", "i", "j"
Using base R you can try
d[] <- lapply(d, function(x) if(is.factor(x)) as.character(x) else x)
Convert all columns to characters in a data.frame
EDIT: 2021-03-01
Beginning with dplyr 1.0.0, the _all()
function variants are superceded. The new way to accomplish this is using the new across()
function.
library(dplyr)
mtcars %>%
mutate(across(everything(), as.character))
With across()
, we choose the set of columns we want to modify using tidyselect helpers (here we use everything()
to choose all columns), and then specify the function we want to apply to each of the selected columns. In this case, that is as.character()
.
Original answer:
You can also use dplyr::mutate_all
.
library(dplyr)
mtcars %>%
mutate_all(as.character)
Convert data.frame column format from character to factor
Hi welcome to the world of R.
mtcars #look at this built in data set
str(mtcars) #allows you to see the classes of the variables (all numeric)
#one approach it to index with the $ sign and the as.factor function
mtcars$am <- as.factor(mtcars$am)
#another approach
mtcars[, 'cyl'] <- as.factor(mtcars[, 'cyl'])
str(mtcars) # now look at the classes
This also works for character, dates, integers and other classes
Since you're new to R I'd suggest you have a look at these two websites:
R reference manuals:
http://cran.r-project.org/manuals.html
R Reference card: http://cran.r-project.org/doc/contrib/Short-refcard.pdf
Convert all data frame character columns to factors
DF <- data.frame(x=letters[1:5], y=1:5, stringsAsFactors=FALSE)
str(DF)
#'data.frame': 5 obs. of 2 variables:
# $ x: chr "a" "b" "c" "d" ...
# $ y: int 1 2 3 4 5
You can use as.data.frame
to turn all character columns into factor columns:
DF <- as.data.frame(unclass(DF),stringsAsFactors=TRUE)
str(DF)
#'data.frame': 5 obs. of 2 variables:
# $ x: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
# $ y: int 1 2 3 4 5
How to convert data.frame column from Factor to numeric
breast$class <- as.numeric(as.character(breast$class))
If you have many columns to convert to numeric
indx <- sapply(breast, is.factor)
breast[indx] <- lapply(breast[indx], function(x) as.numeric(as.character(x)))
Another option is to use stringsAsFactors=FALSE
while reading the file using read.table
or read.csv
Just in case, other options to create/change columns
breast[,'class'] <- as.numeric(as.character(breast[,'class']))
or
breast <- transform(breast, class=as.numeric(as.character(breast)))
How do I convert all numeric columns to character type in my dataframe?
In base R
, we may either use one of the following i.e. loop over all the columns, create an if/else
conditon to change it
dataframe[] <- lapply(dataframe, function(x) if(is.numeric(x))
as.character(x) else x)
Or create an index for numeric columns and loop only on those columns and assign
i1 <- sapply(dataframe, is.numeric)
dataframe[i1] <- lapply(dataframe[i1], as.character)
It may be more flexible in dplyr
library(dplyr)
dataframe <- dataframe %>%
mutate(across(where(is.numeric), as.character))
Convert entire data frame to character class with R dplyr
We just don't need the ()
as it returns character(0)
because it expects an argument in the invocation process. The function expression is evaluated, but the argument expression is empty resulting in a zero length output as the value of the invocation expression
as.character()
#character(0)
library(dplyr)
mtcars %>%
as_tibble() %>%
mutate_all(as.character)
and this has the same effect as
mtcars %>%
as_tibble %>%
mutate_all(character(0))
In the newer versions, use mutate
with across
mtcars %>%
mutate(across(everything(), as.character))
If we are using as.character()
use it with anonymous function call
mtcars %>%
as_tibble() %>%
mutate_all(~ as.character(.))
Related Topics
Divide All Columns by the Value from the 2Nd Column - Apply for All Rows
Deleting Rows in R Based on Values Over Multiple Columns
Regex to Replace Comma to Dot Separator
Splitting a Dataframe into Several Dataframes
How to Get to the Next Line in the R Command Prompt Without Executing
Concatenate String Columns and Order in Alphabetical Order
How to Show Code But Hide Output in Rmarkdown
Creating a New Column Based on Unique Id With Values in R
How to Remove Na from a Factor Variable (And from a Ggplot Chart)
R - Test If a String Vector Contains Any Element of Another List
Rstudio Suddenly Stopped Showing Plots in the Plot Pane
To Find Most Frequently Occuring Element in Matrix in R
How to Specify the Size of a Graph in Ggplot2 Independent of Axis Labels
How to Create a Consecutive Group Number
How to Delete Rows Where All the Columns Are Zero