take the middle 4 characters of a string in one column and place them in another in r

You can take the middle 4 characters of a string in one column and place them in another column in R using the following code:

# Sample data
df <- data.frame(original_string = c("abcdefgh", "ijklmnop", "qrstuvwx"))

# Extract middle 4 characters and place in a new column
df$new_column <- substr(df$original_string, (nchar(df$original_string)/2 - 1), 
                        (nchar(df$original_string)/2 + 2))

# Print the updated data frame
print(df)
326 chars
10 lines

This code will extract the middle 4 characters from the original_string column and place them in a new column called new_column in the dataframe df.

related categories

gistlibby LogSnag