This is my first question, I only recently got into learning R so please be gentle.
X is a dataframe with variables V1 and V2.
set.seed(1)
V1 <- c(20:100)
V2 <- stringi::stri_rand_strings(81, 5)
X <- data.frame(V1, V2)
How do I:
a) Create a new dataframe with selection of rows at which variable V1 contains 5 at the position of the second digit? (meaning rows at which V1 has values 25, 35, 45, etc.)
b) Create a new dataframe with selection of rows from V2 at position at which V1 contains 5 at the position of the second digit? (meaning rows of V2 at which V1 has values 25, 35, 45, etc.)
It is essentially the same dataframe as the previous one but the procedure on constructing it is different.
c) Modify V2 by inserting a symbol(for the sake of question, say "X") between 3. an 4. symbol in V2?
Thank you!
You can do :
temp <- X[substring(X$V1, 2, 2) == 5, ]
So answer to question a) is: temp$V1
and question b) is: temp$V2
For question c), we can use substring
to paste 1st to 3rd letter of V2
, insert "X" in between and the remaining string to create new column as V3
.
temp$V3 <- paste0(substring(temp$V2, 1, 3), 'X', substring(temp$V2, 4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With