R quick tips and tricks

Recently I’ve been working with R and Shiny, here are some code snippets that I’ve found useful:

When you need to cut the string and get the stuff before the space:

temp1 <- sub(" .*", "", your_string)

When you need to cut the string and get the stuff after the space:

temp2 <- sub(".* ", "", your_string)

When you need to cut the string and get the number from the string:

temp3 <- as.numeric(gsub("\\D", "", given_reward_name))

When you need to cut the string and get something between different characters, in this example [ and :

temp4 <- sub(".*\\[(.*):.*","\\1",given_reward_name)

When you want to convert the list to the data frame:

df <- data.frame(reward_name = unlist(your_list))

When you want to split one column in to two:

df <- <- str_split_fixed(df$name_of_the_column, " ", 2)

When you want to split a column by a character:

df <- str_split_fixed(df$name_of_the_column, " ", 2)

When you want to check if there is something in a something:

if(is_this_in %in% df$name_of_the_column)