我有一个数据框,如下所示:
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.campestre
,Abies.alba
,Pyrus.communis
等。
是否可以立即更换或如何更轻松地进行更改?
答案 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