Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除model.matrix后面列名中的空白 我写信给你是因为我需要在矩阵的列名中间去掉空白。我在R工作_R_Whitespace_Model.matrix - Fatal编程技术网

删除model.matrix后面列名中的空白 我写信给你是因为我需要在矩阵的列名中间去掉空白。我在R工作

删除model.matrix后面列名中的空白 我写信给你是因为我需要在矩阵的列名中间去掉空白。我在R工作,r,whitespace,model.matrix,R,Whitespace,Model.matrix,在我的代码中,我刚刚运行了model.matrix命令。它为每个因子添加了一列,因此,如果因子名称中有一些空格,它将在列名中移动 我想删除它们 下面是一个例子 Intercept Region_Factor 1 A Region_Factor 2 A Region_Factor 3 A VarA 10 1 1 0 0 1

在我的代码中,我刚刚运行了model.matrix命令。它为每个因子添加了一列,因此,如果因子名称中有一些空格,它将在列名中移动

我想删除它们

下面是一个例子

Intercept   Region_Factor 1 A   Region_Factor 2 A    Region_Factor 3 A     VarA 10    
    1               1                  0                    0               1  
    1               0                  1                    0               0.52
 .......    
我想获得以下列名称:

Intercept   Region_Factor_1_A    Region_Factor_2_A    Region_Factor_3_A    VarA_10
    1               1                   0                    0               1  
    1               0                   1                    0               0.52
 .......

非常感谢

一个选项是使用
gsub
匹配列名中的空格,并替换为
\uu

colnames(df1) <- gsub(" ", '_', colnames(df1))
或者另一个选项是
chartr

colnames(df1) <- chartr( ' ', '_', colnames(df1))

注意:
gsub
首先在这里回答

您可以使用
colnames
读取列名,将空格替换为
gsub
并将其作为列名放回,其内容如下:

colnames(matrix)=gsub(“,”,colnames(matrix),fixed=TRUE)

colnames(df1) <- chartr( ' ', '_', colnames(df1))
library(tidyverse)
df1 %>%
   rename_all(~ str_replace(., ' ', '_'))