str_remove 适用于矢量和数据框,但不适用于 tibble

str_remove works with vectors and data frames but not with tibble

请考虑以下三个例子:

library(tidyverse)

x_vector <- c("Device=iPhone", "Device=Samsung Galaxy")
x_df <- as.data.frame(c("Device=iPhone", "Device=Samsung Galaxy"))
x_tibble <- as_tibble(c("Device=iPhone", "Device=Samsung Galaxy"))

我现在想删除每个字符串的一部分,即 "Device=" 子字符串。它适用于矢量,它也适用于数据框(如果我指定相应的列),但我得到一个奇怪的结果:

(所需的输出将是下面显示的向量和 df 示例的输出)

output_vector <- str_remove(x_vector, "Device=")
output_df <- str_remove(x_df[,1], "Device=")
output_tibble <- str_remove(x_tibble[,1], "Device=")

任何人都可以解释为什么这不适用于 tibbles 以及我如何让它与 tibbles 一起工作?

谢谢!

问题是 tibble 不会在我们 [,1] 时删除维度。它仍然是一个只有一列的 tibble

library(stringr)
class(x_tibble[,1])
#[1] "tbl_df"     "tbl"        "data.frame"   

class(x_df[,1]) 
#[1] "factor"

相反,我们可以使用 [[ 将列提取为向量,因为 str_remove 需要 vector 作为输入(?str_remove - string -输入向量。可以是字符向量,也可以是可强制转换为一个的向量。)

str_remove(x_tibble[[1]], "Device=")