Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Challenge: Compose Your Own Functions | Functional Programming in Practice
Functions and Functional Programming in R

bookChallenge: Compose Your Own Functions

Uppgift

Swipe to start coding

Create two simple functions and compose them to clean a list of strings.

  • The trim_whitespace function must remove leading and trailing whitespace from each string in the input vector.
  • The to_lowercase function must convert all characters in each string of the input vector to lowercase.
  • The clean_strings function must use both trim_whitespace and to_lowercase to process the input vector and return the cleaned result.

Lösning

Note
Definition

The gsub("^\\s+|\\s+$", "", x) command uses regular expressions to clean up strings:

  • ^\\s+ matches one or more whitespace characters at the start of a string;
  • | means 'or';
  • \\s+$ matches one or more whitespace characters at the end of a string.

gsub replaces all matches of these patterns with an empty string (""), effectively removing all leading and trailing spaces from each element in the vector x. This leaves only the inner content of each string untouched.

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 4
single

single

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Suggested prompts:

Can you explain this in simpler terms?

What are the main points I should remember?

Can you give me an example?

close

bookChallenge: Compose Your Own Functions

Svep för att visa menyn

Uppgift

Swipe to start coding

Create two simple functions and compose them to clean a list of strings.

  • The trim_whitespace function must remove leading and trailing whitespace from each string in the input vector.
  • The to_lowercase function must convert all characters in each string of the input vector to lowercase.
  • The clean_strings function must use both trim_whitespace and to_lowercase to process the input vector and return the cleaned result.

Lösning

Note
Definition

The gsub("^\\s+|\\s+$", "", x) command uses regular expressions to clean up strings:

  • ^\\s+ matches one or more whitespace characters at the start of a string;
  • | means 'or';
  • \\s+$ matches one or more whitespace characters at the end of a string.

gsub replaces all matches of these patterns with an empty string (""), effectively removing all leading and trailing spaces from each element in the vector x. This leaves only the inner content of each string untouched.

Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 4
single

single

some-alt