如何用r中的数据框中的点替换单词之间的所有空格?

时间:2015-03-05 14:46:39

标签: r

我有一个数据框,如下所示:

my.tree <- data.frame(Tree=c("Acer campestre", "Abies alba", "Pyrus communis", "Robinia pseudoacacia", "Tilia cordata"), 
                      Freq=c(23,65,47,69,65))

我想立即用spaces替换单词之间的所有point。我想创建新的data frame(或修改此data frame),其中树名称的单词之间会有分数,例如: Acer.campestreAbies.albaPyrus.communis等。

是否可以立即更换或如何更轻松地进行更改?

3 个答案:

答案 0 :(得分:3)

你可以这样做:

> library(dplyr); mutate(my.tree, Tree = gsub(" ", ".", Tree))

#                  Tree Freq
#1       Acer.campestre   23
#2           Abies.alba   65
#3       Pyrus.communis   47
#4 Robinia.pseudoacacia   69
#5        Tilia.cordata   65

答案 1 :(得分:3)

使用gsub可能更安全(也更常规),但您也可以使用make.names

make.names(my.tree$Tree)
# [1] "Acer.campestre"       "Abies.alba"           "Pyrus.communis"      
# [4] "Robinia.pseudoacacia" "Tilia.cordata" 

甚至chartr

chartr(" ", ".", my.tree$Tree)
# [1] "Acer.campestre"       "Abies.alba"           "Pyrus.communis"      
# [4] "Robinia.pseudoacacia" "Tilia.cordata"   

答案 2 :(得分:2)

你可以这样做:

my.tree$Tree <- gsub(pattern = " ", replacement = ".", x = my.tree$Tree)

> my.tree
#                  Tree Freq
#1       Acer.campestre   23
#2           Abies.alba   65
#3       Pyrus.communis   47
#4 Robinia.pseudoacacia   69
#5        Tilia.cordata   65