如何修剪前导和尾随空格? [英] How to trim leading and trailing whitespace?
问题描述
我在data.frame中的前导和尾随空白时遇到了麻烦.
例如,我想根据特定条件查看data.frame
中的特定row
:
I am having some troubles with leading and trailing whitespace in a data.frame.
Eg I like to take a look at a specific row
in a data.frame
based on a certain condition:
> myDummy[myDummy$country == c("Austria"),c(1,2,3:7,19)]
[1] codeHelper country dummyLI dummyLMI dummyUMI
[6] dummyHInonOECD dummyHIOECD dummyOECD
<0 rows> (or 0-length row.names)
我想知道为什么我没有得到预期的产出,因为我的data.frame
显然存在奥地利这个国家.在查看了我的代码历史记录并尝试找出出了什么问题之后,我尝试了:
I was wondering why I didn't get the expected output since the country Austria obviously existed in my data.frame
. After looking through my code history and trying to figure out what went wrong I tried:
> myDummy[myDummy$country == c("Austria "),c(1,2,3:7,19)]
codeHelper country dummyLI dummyLMI dummyUMI dummyHInonOECD dummyHIOECD
18 AUT Austria 0 0 0 0 1
dummyOECD
18 1
我在命令中所做的所有更改都是在奥地利之后添加了一个空白.
All I have changed in the command is an additional whitespace after Austria.
显然还会出现其他烦人的问题.例如,当我想根据国家/地区"列合并两个框架时.一个data.frame
使用"Austria "
,而另一帧使用"Austria"
.匹配无效.
Further annoying problems obviously arise. Eg when I like to merge two frames based on the country column. One data.frame
uses "Austria "
while the other frame has "Austria"
. The matching doesn't work.
- 有没有一种很好的方法可以在屏幕上显示"空白,以便使我意识到问题所在?
- 我可以删除R中的前导空格和尾随空格吗?
到目前为止,我曾经写过一个简单的Perl
脚本,该脚本删除了空格,但是如果我能以某种方式在R中完成它会很好.
So far I used to write a simple Perl
script which removes the whitespace but it would be nice if I can somehow do it inside R.
推荐答案
可能最好的方法是在读取数据文件时处理尾随空格.如果使用read.csv
或read.table
,则可以设置参数strip.white=TRUE
.
Probably the best way is to handle the trailing whitespaces when you read your data file. If you use read.csv
or read.table
you can set the parameterstrip.white=TRUE
.
如果以后要清理字符串,则可以使用以下功能之一:
If you want to clean strings afterwards you could use one of these functions:
# returns string w/o leading whitespace
trim.leading <- function (x) sub("^\\s+", "", x)
# returns string w/o trailing whitespace
trim.trailing <- function (x) sub("\\s+$", "", x)
# returns string w/o leading or trailing whitespace
trim <- function (x) gsub("^\\s+|\\s+$", "", x)
要在myDummy$country
上使用以下功能之一:
To use one of these functions on myDummy$country
:
myDummy$country <- trim(myDummy$country)
要显示"空白,您可以使用:
To 'show' the whitespace you could use:
paste(myDummy$country)
这将为您显示带引号()括起来的字符串,使空格更容易发现.
which will show you the strings surrounded by quotation marks (") making whitespaces easier to spot.
这篇关于如何修剪前导和尾随空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!