替换 R DataFrame 列名中的空格
在本文中,我们将替换 R 编程语言中数据框列名中的空格。
让我们创建一个 4 列 3 行的数据框:
R
# create a dataframe with 4 columns and 3 rows
data = data.frame("web technologies" = c("php","html","js"),
"backend tech" = c("sql","oracle","mongodb"),
"middle ware technology" = c("java",".net","python"))
# display
data
R
# create a dataframe with 4 columns and 3 rows
data=data.frame("web technologies"=c("php","html","js"),
"backend tech"=c("sql","oracle","mongodb"),
"middle ware technology"= c("java",".net","python"),
check.names=FALSE)
# replace blank with underscore
print( gsub(" ", "_", colnames(data)))
# replace blank with dot operator
print( gsub(" ", ".", colnames(data)))
# replace blank with * operator
print( gsub(" ", "*", colnames(data)))
R
# create a dataframe with 4 columns and 3 rows
data = data.frame("web technologies" = c("php","html","js"),
"backend tech" = c("sql","oracle","mongodb"),
"middle ware technology" = c("java",".net","python"),
check.names = FALSE)
# replace blank by using make.names
print( make.names(colnames(data)))
输出:
在上面的例子中,我们可以看到列名中有空格,所以我们将替换这些空格
方法一:使用 gsub()函数
在这些方法中,我们将使用 gsub函数,R 语言中的 gsub()函数用于替换字符串模式的所有匹配项。如果未找到模式,则字符串将按原样返回。
Syntax: gsub(” “, “replace”, colnames(dataframe))
Parameters:
- first parameter takes space
- second parameter takes replacing character that replaces blank space
- third parameter takes column names of the dataframe by using colnames() function
示例: R 程序创建一个数据框并用不同的符号替换数据框列
电阻
# create a dataframe with 4 columns and 3 rows
data=data.frame("web technologies"=c("php","html","js"),
"backend tech"=c("sql","oracle","mongodb"),
"middle ware technology"= c("java",".net","python"),
check.names=FALSE)
# replace blank with underscore
print( gsub(" ", "_", colnames(data)))
# replace blank with dot operator
print( gsub(" ", ".", colnames(data)))
# replace blank with * operator
print( gsub(" ", "*", colnames(data)))
输出:
[1] “web_technologies” “backend__tech” “middle_ware_technology”
[1] “web.technologies” “backend..tech” “middle.ware.technology”
[1] “web*technologies” “backend**tech” “middle*ware*technology”
方法二:使用 make.names()函数
我们可以通过使用 make.names()函数来做到这一点。
Syntax: make.names(colnames(dataframe))
Where, dataframe is the input dataframe
示例:使用 make.names 替换数据框列名的 R 程序
电阻
# create a dataframe with 4 columns and 3 rows
data = data.frame("web technologies" = c("php","html","js"),
"backend tech" = c("sql","oracle","mongodb"),
"middle ware technology" = c("java",".net","python"),
check.names = FALSE)
# replace blank by using make.names
print( make.names(colnames(data)))
输出:
[1] “web.technologies” “backend..tech” “middle.ware.technology”