在R中的数据帧中的两个字符之间添加空格 [英] Adding a space between two characters in a data frame in R

查看:1499
本文介绍了在R中的数据帧中的两个字符之间添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中每个单元格是2个字符串(即:AA,BC,CD),其中我试图在每个两个字符之间放置空格,是。我似乎不明白这一点。任何帮助????

I have a data frame where each cell are 2 character strings (ie: "AA" , "BC" , "CD") where I am trying to put spaces between each of the two characters, and where NA values remain as is. I can't seem to figure this out. Any help????

以下是示例数据框:

 df <- data.frame(col1=c("AB", "CD", "EF"), col2=c("AA", "BB", "CC"), col3=c("XX", "YY", NA))

这是示例数据框架的样子: / p>

And this is what the example data frame looks like:

   col1 col2 col3
1   AB   AA   XX
2   CD   BB   YY
3   EF   CC <NA>

这是我想要的数据框看起来像:

This is what i want my data frame to look like:

   col1  col2  col3
1   A B   A A   X X
2   C D   B B   Y Y
3   E F   C C   <NA>

提前感谢!

推荐答案

以下是一种方法

df2 <- data.frame(lapply(df, function(x) {
  levels(x) <- gsub("(.)(.)", "\\1 \\2", levels(x))
  return(x)
}))

df2

#   col1 col2 col3
# 1  A B  A A  X X
# 2  C D  B B  Y Y
# 3  E F  C C <NA>

这当然需要假设在创建data.frame df 参数 stringsAsFactors TRUE

This of course relies on the assumption that, when creating the data.frame df the argument stringsAsFactors is TRUE.

这篇关于在R中的数据帧中的两个字符之间添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆