你的顺序不好:
在这里, 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"