仅删除数据集定性值前面的空白?
Remove only the blanks in front of the qualitative values of a dataset?
我在 R 中有一个包含多个列的数据集。其中一些包含定性值,其第一个字符为空白 space。我想知道如何只删除定性值前面的空白。例如,“Living room”应该是“Living room”。我考虑过实现 str_replace 函数并包含允许这样做的模式,但是,我需要在数据集的多个列中执行此过程。
有更好的主意吗?
str_replace(df$column, *pattern*)
您可以使用 dplyr
包中的 mutate()
和 across()
跨数据框的多个变量(即列)使用 trims()
。首先,这是一些玩具数据:
df <- data.frame(
id = c(1,2, 3),
var1 = c(" Living Room", " Kitchen", " Great Room"),
var2 = c(" Guest Room", " Master Bedrom", " Bathroom"),
var3 = c(" Office", " Laundry Room", " Casita")
)
df %>% glimpse()
输出:
Rows: 3
Columns: 4
$ id <dbl> 1, 2, 3
$ var1 <chr> " Living Room", " Kitchen", " Great Room"
$ var2 <chr> " Guest Room", " Master Bedrom", " Bathroom"
$ var3 <chr> " Office", " Laundry Room", " Casita"
library(dplyr)
df <- df %>%
mutate(
across(starts_with("var"), trimws)
)
df %>% glimpse()
输出:
Rows: 3
Columns: 4
$ id <dbl> 1, 2, 3
$ var1 <chr> "Living Room", "Kitchen", "Great Room"
$ var2 <chr> "Guest Room", "Master Bedrom", "Bathroom"
$ var3 <chr> "Office", "Laundry Room", "Casita"
我在 R 中有一个包含多个列的数据集。其中一些包含定性值,其第一个字符为空白 space。我想知道如何只删除定性值前面的空白。例如,“Living room”应该是“Living room”。我考虑过实现 str_replace 函数并包含允许这样做的模式,但是,我需要在数据集的多个列中执行此过程。
有更好的主意吗?
str_replace(df$column, *pattern*)
您可以使用 dplyr
包中的 mutate()
和 across()
跨数据框的多个变量(即列)使用 trims()
。首先,这是一些玩具数据:
df <- data.frame(
id = c(1,2, 3),
var1 = c(" Living Room", " Kitchen", " Great Room"),
var2 = c(" Guest Room", " Master Bedrom", " Bathroom"),
var3 = c(" Office", " Laundry Room", " Casita")
)
df %>% glimpse()
输出:
Rows: 3
Columns: 4
$ id <dbl> 1, 2, 3
$ var1 <chr> " Living Room", " Kitchen", " Great Room"
$ var2 <chr> " Guest Room", " Master Bedrom", " Bathroom"
$ var3 <chr> " Office", " Laundry Room", " Casita"
library(dplyr)
df <- df %>%
mutate(
across(starts_with("var"), trimws)
)
df %>% glimpse()
输出:
Rows: 3
Columns: 4
$ id <dbl> 1, 2, 3
$ var1 <chr> "Living Room", "Kitchen", "Great Room"
$ var2 <chr> "Guest Room", "Master Bedrom", "Bathroom"
$ var3 <chr> "Office", "Laundry Room", "Casita"