I want to be able to slice a character string based on a numeric value in a dataframe. The value will vary across rows.
I have a df that looks like:
df <- data.frame(List.obs = "SNP" "NSBP" "SPNCF" "NPSB" "SPN" "PNS"),
n = c(3,4,5,4,3,3))
I want to add a column to it called “pred.obs” that contains the number of characters listed in df$n of the string “NSPBFC”. so the df should look like:
List.obs | n | pred.obs |
---|---|---|
SNP | 3 | NSP |
NSBP | 4 | NSPB |
SPNCF | 5 | NSPBF |
NPSB | 4 | NSPB |
SPN | 3 | NSP |
PNS | 3 | NSP |
I have tried:
df %>% mutate(pred.obs = substr("NSPBFC", 1, df$n))
to no avail. It only returns “NSP” for all rows. Any thoughts?
Thanks in advance