Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using dplyr's mutate_each to coerce a dataframe to character values
mtcars %>% tbl_df() %>% mutate_each(funs(as.character))
# Source: local data frame [32 x 11]
#
# mpg cyl disp hp drat wt qsec vs am gear carb
# 1 21 6 160 110 3.9 2.62 16.46 0 1 4 4
# 2 21 6 160 110 3.9 2.875 17.02 0 1 4 4
# 3 22.8 4 108 93 3.85 2.32 18.61 1 1 4 1
# 4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# 5 18.7 8 360 175 3.15 3.44 17.02 0 0 3 2
# 6 18.1 6 225 105 2.76 3.46 20.22 1 0 3 1
# 7 14.3 8 360 245 3.21 3.57 15.84 0 0 3 4
# 8 24.4 4 146.7 62 3.69 3.19 20 1 0 4 2
# 9 22.8 4 140.8 95 3.92 3.15 22.9 1 0 4 2
# 10 19.2 6 167.6 123 3.92 3.44 18.3 1 0 4 4
# .. ... ... ... ... ... ... ... .. .. ... ...
mtcars %>% tbl_df() %>% mutate_each(funs(as.character)) %>% glimpse
# Observations: 32
# Variables:
# $ mpg (chr) "21", "21", "22.8", "21.4", "18.7", "18.1", "14.3", "24.4", "22.8", "19.2", "17.8"...
# $ cyl (chr) "6", "6", "4", "6", "8", "6", "8", "4", "4", "6", "6", "8", "8", "8", "8", "8", "8...
# $ disp (chr) "160", "160", "108", "258", "360", "225", "360", "146.7", "140.8", "167.6", "167.6...
# $ hp (chr) "110", "110", "93", "110", "175", "105", "245", "62", "95", "123", "123", "180", "...
# $ drat (chr) "3.9", "3.9", "3.85", "3.08", "3.15", "2.76", "3.21", "3.69", "3.92", "3.92", "3.9...
# $ wt (chr) "2.62", "2.875", "2.32", "3.215", "3.44", "3.46", "3.57", "3.19", "3.15", "3.44", ...
# $ qsec (chr) "16.46", "17.02", "18.61", "19.44", "17.02", "20.22", "15.84", "20", "22.9", "18.3...
# $ vs (chr) "0", "0", "1", "1", "0", "1", "0", "1", "1", "1", "1", "0", "0", "0", "0", "0", "0...
# $ am (chr) "1", "1", "1", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0...
# $ gear (chr) "4", "4", "4", "3", "3", "3", "3", "4", "4", "4", "4", "3", "3", "3", "3", "3", "3...
# $ carb (chr) "4", "4", "1", "1", "2", "1", "4", "2", "2", "4", "4", "3", "3", "3", "4", "4", "4...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment