Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

r - How to properly remove NA's and convert strings to title in the same pipeline?

I am trying to drop NA values for a df column and then str_to_title() all column observations, currently I am using library(tidyr) to drop NA and library(stringr) to convert to title.

Here's the code:

library(tidyr)
library(stringr)

test <- df %>% 
  tidyr::drop_na(string_column) %>%
  stringr::str_to_title(string_column)

Here's the error:

Error in stri_opts_brkiter(locale = locale) : 
  objeto 'string_column' no encontrado

Expected output should look like this:

# string_column   numeric_column
#  Debit               100
#  Credit              100
#  Debit               100
#  Credit               0
#  Debit                0
#  Credit               80

data

df <- data.frame(string_column = c(NA, "DEBIT", "Credit", "Debit", "CREDIT", "DEBIT","CREDIT", NA),
                 numeric_column = c(0, 100, 100, 100, 0, 0, 80,80))

How could I adjust the pipeline to get the expected output?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try using dplyr::mutate to alter the values of the column string_column using stringr::str_to_title.

df %>% 
  tidyr::drop_na(string_column) %>%
  mutate(string_column = stringr::str_to_title(string_column))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...