Why are my row names dropped and how to avoid it?

梦想的初衷 提交于 2019-12-11 03:34:15

问题


I want to replace a certain string by another in a data frame here is a sample code:

table_ex <- data.frame(row.names = c("row 1", "row 2", "row 3"))
table_ex$year1 <- 3:1
table_ex$year2 <- c("NaN", 5, "NaN %")
table_ex$year3 <- c("NaN %", 7, "NaN %")

remove_symb <- function(yolo){stringr::str_replace(yolo, 'NaN %|NaN', '')}
table_ex <- mutate_all(table_ex, funs(remove_symb))

Doing the above is dropping my rownnames. I understand I could use a lapply function, but I'm wondering why are the row names dropped. Is it because of the str_replace functions or the mutate_all functions? And how should I prevent that?


回答1:


If we need to keep the row names, loop through the columns and assign it back to the original data and to keep the structure intact use [].

table_ex[] <- lapply(table_ex, remove_symb)
table_ex
#      year1 year2 year3
#row 1     3            
#row 2     2     5     7
#row 3     1            

Using dplyr or data.table will change the row names to numeric sequence, but with [], we can still change it to the original row names

table_ex[] <- mutate_all(table_ex, funs(remove_symb))


来源:https://stackoverflow.com/questions/40968821/why-are-my-row-names-dropped-and-how-to-avoid-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!