deschen
deschen

Reputation: 11006

str_remove works with vectors and data frames but not with tibble

Please consider the following three examples:

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

I now want to remove part of each string, i.e. the "Device=" sub string. It works for a vector, it also works for a data frame (if I specify the respective column), but I get a weird result for a tibble:

(the desired output would be the ones shown below for the vector and df example)

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

Can anyone please explain why this doesn't work with tibbles and how I can get it working with tibbles?

Thanks!

Upvotes: 2

Views: 1028

Answers (1)

akrun
akrun

Reputation: 887541

The issue is that tibble won't drop the dimensions when we do [,1]. It is a still a tibble with a single column.

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

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

Instead, we can use [[ to extract the column as a vector because str_remove expects a vector as input (?str_remove - string - Input vector. Either a character vector, or something coercible to one.)

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

Upvotes: 1

Related Questions