为什么我的行名被删除以及如何避免呢? [英] Why are my row names dropped and how to avoid it?

查看:52
本文介绍了为什么我的行名被删除以及如何避免呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用数据框中的另一个字符串替换某个字符串这是示例代码:

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))

执行上述操作会删除我的行名.我知道我可以使用lapply函数,但是我想知道为什么行名被删除.是因为 str_replace 函数还是 mutate_all 函数?而我应该如何防止呢?

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?

推荐答案

如果我们需要保留行名,请遍历各列,并将其分配回原始数据,并使用 [].

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            


使用 dplyr data.table 将行名更改为数字序列,但是使用 [] ,我们仍然可以将其更改为原始行名


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))

这篇关于为什么我的行名被删除以及如何避免呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆