Reputation: 5719
I have this dataframe called mydf
. I want to add a /
after each element in each column and get the result.
mydf
rowname val1 val2 val3
1 00 100 111
2 01 11 11
3 00 01 01
result
rowname val1 val2 val3
1 0/0 1/0/0 1/1/1
2 0/1 1/1 1/1
3 0/0 0/1 0/1
Upvotes: 1
Views: 52
Reputation: 887671
We can loop over the 'val' columns with lapply
and use regex lookaround pattern using gsub
and replace by /
.
mydf[-1] <- lapply(mydf[-1], function(x)
gsub('(?<=\\d)(?=\\d)', '/', x, perl=TRUE))
mydf
# rowname val1 val2 val3
# 1 1 0/0 1/0/0 1/1/1
# 2 2 0/1 1/1 1/1
# 3 3 0/0 0/1 0/1
mydf <- structure(list(rowname = c("1", "2", "3"),
val1 = c("00", "01",
"00"), val2 = c("100", "11", "01"), val3 = c("111", "11", "01"
)), .Names = c("rowname", "val1", "val2", "val3"),
class = "data.frame", row.names = c(NA, -3L))
Upvotes: 3
Reputation: 174796
Just apply the below logic on every column.
gsub("(.)(?=.)", "\\1/", x, perl=TRUE)
Upvotes: 3