我想遍历所有行并重命名它们。基本上我只想在我的数据框中删除一些单词(每个行名称中的相同模式)。
代码:
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*
,值= c(“我想删除的字词”,: 无效的'row.names'长度
请注意,代码在循环之外工作正常。
答案 0 :(得分:1)
你的顺序不好:
在这里,我在rownames(df)中依次是你的每个名字:
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"]
,即:row.names(mtcars)["Mazda RX4"]
返回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"