0

我想遍历我的所有行并重命名它们。基本上我只想在我的数据框中删除一些单词(每行名称中的相同模式)。

代码:

for (i in rownames(df)) {

  row.names(df)[i] <- gsub("*The words I want to remove*", "", row.names(df)[i])
}

我收到以下错误:

row.names<-.data.frame( *tmp*, value = c(" The words I want to remove ", : invalid 'row.names' length

请注意,代码在循环之外可以正常工作。

4

1 回答 1

1

你的顺序不好:

在这里, i in rownames(df) 依次是您的每个 rown 名称:

for (i in rownames(mtcars)) {
+   print(i)
+ }
[1] "Mazda RX4"
[1] "Mazda RX4 Wag"
[1] "Datsun 710"
...

所以row.names(df)[i]正在尝试做row.names(df)["yourrowname"]ie : row.names(mtcars)["Mazda RX4"]which return NA。

您编写代码的方式i必须是一个数字。所以 :

for (i in seq_along(rownames(df))) {
  print(i)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
... 

现在,要替换行名,您需要将 i 括起来。这是 mtcars 的示例:

data("mtcars")
rownames(mtcars)
[1] "Mazda RX4"           "Mazda RX4 Wag"      
[3] "Datsun 710"          "Hornet 4 Drive"     
[5] "Hornet Sportabout"   "Valiant"            
[7] "Duster 360"          "Merc 240D"          
[9] "Merc 230"            "Merc 280"           
[11] "Merc 280C"           "Merc 450SE"         
[13] "Merc 450SL"          "Merc 450SLC"        
[15] "Cadillac Fleetwood"  "Lincoln Continental"

for (i in seq_along(rownames(mtcars))) {

  row.names(mtcars)[[i]] <- gsub(" ", "_", row.names(mtcars)[[i]])
}
rownames(mtcars)

[1] "Mazda_RX4"           "Mazda_RX4_Wag"      
[3] "Datsun_710"          "Hornet_4_Drive"     
[5] "Hornet_Sportabout"   "Valiant"            
[7] "Duster_360"          "Merc_240D"          
[9] "Merc_230"            "Merc_280"           
[11] "Merc_280C"           "Merc_450SE"         
[13] "Merc_450SL"          "Merc_450SLC" 

但正如评论中所述,您不需要 for 循环:

rownames(mtcars) <- gsub(" ", "_", row.names(mtcars))
rownames(mtcars)
[1] "Mazda_RX4"           "Mazda_RX4_Wag"      
[3] "Datsun_710"          "Hornet_4_Drive"     
[5] "Hornet_Sportabout"   "Valiant"            
[7] "Duster_360"          "Merc_240D"          
[9] "Merc_230"            "Merc_280"           
[11] "Merc_280C"           "Merc_450SE"         
[13] "Merc_450SL"          "Merc_450SLC"  
于 2017-10-02T10:29:14.383 回答