简体   繁体   English

将R中数据框中的所有值转换为字符串

[英]Converting to string all values in a data frame in R

How can I make sure each single value contained in a dataframe is a string ? 如何确定数据框中包含的每个单个值都是字符串

Moreover, is there a way I can add a prefix to each value contained in a dataframe? 此外,有没有一种方法可以向数据帧中包含的每个值添加前缀 (for example, turning a 0.02 to "X0.02" ) (例如,将0.02更改为"X0.02"

We can loop through the columns of the data.frame with lapply , convert to character and assign the output back to the dataset. 我们可以遍历的列data.framelapply ,转换为character和输出分配回的数据集。 The [] is used to preserve the attributes of the original data and not output as a list element []用于保留原始数据的属性,而不作为list元素输出

dat[] <- lapply(dat, as.character)

Or if there is at least one character element, conversion to matrix and then back to data.frame will also make sure the elements are character 或者,如果至少有一个字符元素,则转换为matrix然后再返回到data.frame还将确保元素是character

as.data.frame(as.matrix(dat), stringsAsFactors = FALSE)

For the second case 对于第二种情况

dat[] <- lapply(dat,function(x) paste0("X", x))

Or in tidyverse 或在tidyverse

library(dplyr)
library(stringr)
dat %>%
   mutate_all(list(~ str_c("X", .)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM