find all string objects in r

To find all string objects in R, you can use the sapply() function with is.character function as an argument. This function will return a logical vector indicating whether each element of the input is a character string or not.

main.r
# Create a sample list with different types of data
my_list <- list("hello", 1:5, TRUE, "world", 6:10, "foo")

# Use `sapply()` with `is.character` function to identify string objects
all_strings <- sapply(my_list, is.character)

# Subset the original list to extract only string objects
string_objects <- my_list[all_strings]

print(string_objects)
# Output: 
# [[1]]
# [1] "hello"
# 
# [[2]]
# [1] "world"
# 
# [[3]]
# [1] "foo"
431 chars
20 lines

You can also use the grep() function with a regular expression pattern to search for string objects in a specific variable or data frame. For example:

main.r
# Create a data frame with different types of data
df <- data.frame(
  col1 = c("hello", "world", "foo"),
  col2 = c(1:3),
  col3 = c(FALSE, TRUE, FALSE)
)

# Use `grep()` to identify string objects in `col1`
string_indices <- grep("[a-z]+", df$col1)

# Subset the original data frame to extract only rows with string objects in `col1`
df_strings <- df[string_indices, ]

print(df_strings)
# Output: 
#     col1 col2  col3
# 1  hello    1 FALSE
# 2  world    2  TRUE
# 3    foo    3 FALSE
489 chars
20 lines

gistlibby LogSnag