为什么我的行名称被删除以及如何避免?
Why are my row names dropped and how to avoid it?
我想用数据框中的另一个字符串替换某个字符串
这是一个示例代码:
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
函数?我该如何预防?
如果我们需要保留行名,遍历列并将其分配回原始数据并保持结构完整,请使用 []
.
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
会将行名更改为数字序列,但使用[]
,我们仍然可以将其更改为原始行名
table_ex[] <- mutate_all(table_ex, funs(remove_symb))
我想用数据框中的另一个字符串替换某个字符串 这是一个示例代码:
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
函数?我该如何预防?
如果我们需要保留行名,遍历列并将其分配回原始数据并保持结构完整,请使用 []
.
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
会将行名更改为数字序列,但使用[]
,我们仍然可以将其更改为原始行名
table_ex[] <- mutate_all(table_ex, funs(remove_symb))